Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
602 views
in Technique[技术] by (71.8m points)

javascript - Getting wrong canvas height

I get a wrong canvas height. Whats wrong here? I made a fiddle: http://jsfiddle.net/hbcz6/

HTML:

<div id="app">
    <div id="percent" class="animated"></div>
    <canvas></canvas>
</div>

Javascript:

var canvas = document.getElementsByTagName("canvas")[0];

var context = canvas.getContext('2d');
var x = canvas.width / 2;
console.log("canvas X: ", x);
var y = canvas.height / 2;
console.log("canvas y: ", y);

Please have a look to your console.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As you are not setting the size of the canvas element its bitmap will default to 300 x 150 pixels. If you use CSS rules then the element will be stretched but the bitmap will, stay at the same size just scaled to fit the size of the element (just like an image would).

Here is how to dynamically fit a canvas element inside a parent element settings its size properly:

First, remove the width and height from the CSS rule:

#app canvas {
    border:2px solid red;
    }

Then use getComputedStyle to get the parent element's dimension in pixels:

var cs = getComputedStyle(app),
    width = parseInt(cs.getPropertyValue('width'), 10);
    height = parseInt(cs.getPropertyValue('height'), 10);

The parseInt will remove the px at the end - now simply use those for the canvas element:

canvas.width = width;
canvas.height = height;

Working fiddle here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...