Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 canvas resize to parent

Tags:

I want to resize the canvas element so that if fits its parent, whether it's <body> ("full-screen") or some <div> for instance. This is my attempt:

// called at each frame function update() {     var canvasNode = document.getElementById('mycanvas');     canvasNode.width = canvasNode.parentNode.clientWidth;     canvasNode.height = canvasNode.parentNode.clientHeight; } 

For some reason, the canvas doesn't stop growing! Maybe client* aren't the right parameters?

See the code in action here: http://jsfiddle.net/ARKVD/24/

like image 902
Giovanni Funchal Avatar asked Dec 24 '11 11:12

Giovanni Funchal


2 Answers

The easiest thing to do is to always keep the canvas in its own div.

The only thing that will ever be in this div is the canvas.

Then you can use CSS to resize the div however you want. You want it as large as the body? Give the div width: 100%.

Then you can always rightfully do:

canvas.width = theDiv.clientWidth; canvas.height = theDiv.clientHeight; 

If you do this you won't have to worry about the weird issues that you're currently facing when the body is the direct parent of the div.

like image 57
Simon Sarris Avatar answered Sep 20 '22 15:09

Simon Sarris


You can workaround the problem by breaking the circular dependency between the parent node and the child node. The size allocation of the DOM elements should only propagate top-down (from the parent to the child). You can ensure that the child element (canvas) does not affect the parent's size by setting

canvasNode.style.position = 'absolute'; 

This puts it into its own document flow that is independent of the parent.

like image 28
Imran Avatar answered Sep 20 '22 15:09

Imran