Blog about (Web-) Programming, Graphics and Games.

10.02.2010

Html5-Canvas with variable size

I tried to make a Html-page with a Canvas-element, which fills the whole page or browser window. Following line
<canvas width="100%" height="100%">
didnt work. It produced a canvas with a dimension of 100x100 pixels. Following
<canvas style="width:100%;height:100%" width="100%" height="100%">
worked a bit better: the canvas filled the browser window. Though the canvas still had a size of 100x100 pixels, but it was scaled up to fit the page. To have a canvas that dynamically changes its size according to the browser window, I had to set canvas.width and .height manually, like in this code snippet:
var cont=canvas.parentNode;
if ((canvas.width!=cont.clientWidth)||(canvas.height!=cont.clientHeight)) {
canvas.width=cont.clientWidth;
canvas.height=cont.clientHeight;}
Note: by setting e.g. canvas.width the canvas will be cleared, so the resize must take place before the repaint.

Update: If the canvas is used with WebGL, the gl-viewport must be set to the new size.
gl.viewport(0,0,canvas.width,canvas.height);

3 Kommentare:

Anonym hat gesagt…

Hey,

I have a message for the webmaster/admin here at pl4n3.blogspot.com.

Can I use part of the information from your blog post above if I give a link back to your site?

Thanks,
John

pl4n3 hat gesagt…

Yes you can use the source this way, its nice that you find it usefull. :)
Cheers,
Peter

Anonym hat gesagt…

Thanks for sharing this link, but unfortunately it seems to be offline... Does anybody have a mirror or another source? Please reply to my message if you do!

I would appreciate if someone here at pl4n3.blogspot.com could post it.

Thanks,
Oliver