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/
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With