HTML5 canvas resize to parent

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/

Answers:

Answer

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.

Answer

I've found that the cleanest approach is to simply "remind" the canvas element how big it's supposed to be upon resize:

window.onresize = function () {
    canvas.style.width = '100%';
    canvas.height = canvas.width * .75;
}

The height setting in this case is there to simply maintain a 4:3 ratio. You can, of course, make it 100% as well if you desire.

Answer

I found the same problem happening, and the only way I could find to work around it was to set the canvas height to parentHeight - 1. This was using CEF. In this fiddle I had to set it to parentHeight - 5.

canvasNode.height = div.clientHeight - 5;
Answer

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.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.