当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - How To Get Width Of Canvas Placed On Responsive HTML Page

问题描述:

My HTML File

<div id="canvas">

<canvas id="myCanvas">

</div>

My CSS FIle

#canvas

{

width:100%;

height:100%;

}

#myCanvas

{

width:100%;

height:40%;

}

Using Javascript I Am Drawing An Image On Canvas (Redraw After 1 Second). This Page Is Responsive. So Canvas Width Changes As Browser Width Change. In ImageDraw Function I Am Trying To Get Width Of Canvas

c = document.getElementById("myCanvas");

ctx = c.getContext("2d");

canvaswidth = c.width;

But Even After Changing Width Of Browser I Am Getting Canvas Width As 300. What Is The Issue.

网友答案:

The actual dimensions of the HTMLCanvasElement are defined by its "width" and "height" properties, which are different from the CSS style-declaration ! Setting the CSS attributes different to those of the canvas' width and height will result in scaling the canvas by the browser, as if you were zooming content.

To match your expectancy what you'd want is to explicitly set the width and height of the canvas to match the percentages you'd expect from the CSS declartions, i.e. : measure the dimensions in pixels of the canvas' parent container (let's assume 320px width in this example), multiply it by the percentage of choice (let's say 90% which is 320 * .9 == 288 pixels) and set it onto the canvas' width property, do the same for the height et voila.

Note: this has implications for your draw-methods, depending on how you're drawing the content onto the canvas (i.e. when using absolute values for coordinates and dimensions) it might actually be more feasible to just have it scaled by CSS !

分享给朋友:
您可能感兴趣的文章:
随机阅读: