开发者

enlarging canvas to parent width and height

I am trying to draw some shapes on the HTML5 canvas using Javascript.

When the width and height of the canvas is of a hard coded size like for example 800x600 everything works fine.

What I would like to do is to stretch the width of the canvas to fit the parent (the size of the parent can be anything). When I apply the width: 100% and height: 100% properties in the CSS, the shapes drawn start from a different starting point from what开发者_JAVA百科 it actually should.

A sample of what I am working on is provided in this link: http://jsfiddle.net/jR4ne/

Please help me out in understanding what is going wrong here. It appears that the canvas is being stretched instead of being enlarged. I want the canvas to be enlarged to fit the parent.


For your case, you shouldn't use CSS to change the size. You have to specify the width and height in pixel for Canvas. You can add the code below to your JS () and it will meet your requirement:

canvasNode.width = document.body.scrollWidth;
canvasNode.height = document.body.scrollHeight;

Of course, your parent may refer to different things, you need to change the width and height accordingly. Please refer to here for more info: http://www.howtocreate.co.uk/tutorials/javascript/browserwindow


It looks like the canvas is being initialised too early, before it has been resized to width 100%: the drawn rectangles also render in stretched mode. I would suggest putting the initialisation code into an onload function e.g.

<body onload="setupCanvas()">

or with jQuery:

$( function() { setupCanvas(); } );

I would also suggest removing the width/height attributes from the HTML (not sure if they are just there temporarily as the css width 100% is not working?)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜