Andrew Howard
Andrew Howard

Reputation: 3072

Set all <canvas>'s in the html document to the document's width and height?

Without the use of jquery (ie only using old javascript), how can I set all canvas's in the html document to the document's width and height?

Upvotes: 0

Views: 397

Answers (2)

nealio82
nealio82

Reputation: 2633

I've created a jsFiddle here: http://jsfiddle.net/ZrfeV/

You will need to give the document a height so the canvas knows how big to expand to, otherwise it will expand to whatever height the document gains by the internal height of its child elements.

var canvases = document.getElementsByTagName('canvas');

for (var i = 0; i < canvases.length; i++) {

    canvases[i].style.width = '100%';
    canvases[i].style.height = '100%';
    canvases[i].width = canvases[i].clientWidth;
    canvases[i].height = canvases[i].clientHeight;

}

Upvotes: 1

Matt Wonlaw
Matt Wonlaw

Reputation: 12443

Note: Both Chief's and Naelio's answers are technically incorrect.


Naelio: Changing the canvas's style will change the canvas's CLIENT WIDTH and CLIENT HEIGHT not the actual width and height so the content of the canvas will end up being scaled / stretched.
Example of this problem here: http://jsfiddle.net/AnLCw/1/ (note how the black 50x50 square is stretched using the style approach)


Chief17: You can't specify the width and height of a canvas in percentages. Example of the problem here: http://jsfiddle.net/Sg7cb/2/ (note that no canvas shows up when width and height are percentages)


So here is the actual solution:

You need to set the canvas's style to be: width: 100% and height: 100%

canvas.style.width = "100%"
canvas.style.height = "100%"

and then do:

canvas.width = canvas.clientWidth
canvas.height = canvas.clientHeight

Working example here: http://jsfiddle.net/acYdc/1/ (Notice how the black square draws correctly and the canvas fills the area.)

Another solution is just to set

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

but the canvas.width = canvas.clientWidth approach is more flexible.

Upvotes: 2

Related Questions