I work on a canvas-based application and I needed to resize the canvas dynamically. The thing is, setting width and height through CSS stretches the canvas instead of actually widening the drawing surface. You need to set that through the html width and height attributes, in pixels. That's the problem: I wanted it to fill the table cell.
I worked out a solution thanks to a few lines of javascript I found on another SE answer.
canvas.width = canvas.offsetWidth;
canvas.height = canvas.offsetHeight;
The offsetWidth property takes the CSS height into account, so it can be used to transform the 100% height into a pixel value. So we let the css resize the canvas element and we us JS to resize the drawing surface... But it seems to only work when trying to make the canvas grow.
http://jsfiddle.net/4p18g0e9/1/
Look at this fiddle in chrome. As you resize the result window, the canvas gets redrawn and resized so the red square always has the same aspect ratio. However, when you try to shrink the window, the canvas keeps the same size, overflowing below the body! I added the css code to draw a border under to body to show this.
In firefox, the CSS height of 100% on the canvas seems to make it wider than the page instead of making it relative to the parent. Remove the JS from the fiddle and try it, the canvas is huge.
I've worked out a fix for chrome's problem here: http://jsfiddle.net/yb6e9mwa/2/
updateCanvasSize = function() {
canvas.width = 0;
canvas.height = 0;
canvas.style.width = "1px";
canvas.style.height = "1px";
setTimeout(_updateCanvasSize, 0);
};
_updateCanvasSize = function() {
canvas.style.width = "100%";
canvas.style.height = "100%";
canvas.width = canvas.offsetWidth;
canvas.height = canvas.offsetHeight;
drawCanvas();
};
It's quite simple, I just set both the height and the CSS height to 0px, wait for it to render and then set it back to what it should. It works fine, even though it means you can't see the canvas while resizing the window.
That fix on Firefox, however, sets the canvas to a constant 1px high. Is there something wrong with the browsers, or am I doing something wrong?
td, eg jsfiddle.net/yb6e9mwa/3, does it help? - mido