You're correct when you said:
"[the div doesn't decrease] I guess that's because it contains the canvas"
The accepted answer suggests using the css width property with a caveat that the canvas will stretch. This is also completely correct; the canvas will stretch.
You might want the canvas to stretch, but this is usually not desirable. For completeness, here is an answer to actually resize the canvas.
For best results, you need to use the following logic:
Steps
- Capture the resize event, which you've done, and then...
- Hide the canvas
- Measure the parent div size
- Re-size the canvas's width and height properties to match the measured parent div size
- Re-show your canvas
- Redraw your canvas graphics. This is an important extra step. Anytime you manually re-size the canvas the existing graphics are cleared.
The last step, redrawing graphics, is really important. A detailed explanation on how to redraw graphics with the correct scaling can be found here:
html5 canvas redraw on resize
Demo
A demo of this logic working can be found here:
http://spencer-evans.com/share/github/canvas-resizer/
JavaScript Solution
In JavaScript, a solution is:
// Call this every time the canvas resizes
function resizeCanvas()
{
// Grab the canvas and it's parent div
var canvas = document.getElementById("myCanvasId");
var parent = canvas.parentNode;
// Hide the canvas so we can get the parent's responsive bounds
var displayBackup = canvas.style.display;
canvas.style.display = "none";
// Measure parent without the canvas
var w = parent.clientWidth;
var h = parent.clientHeight;
// Set the new canvas dimensions
canvas.width = w;
canvas.height = h;
// Restore the canvas display property
canvas.style.display = displayBackup;
// IMPORTANT: Call code here to redraw canvas graphics!
}
Library Solution
This can be cumbersome and I've ran into it time and time again. I've written a small JS / typescript library to handle this. You can find the library here:
https://github.com/swevans/canvas-resizer
The library also has the benefit of re-sizing the canvas to match high resolution displays where devicePixelRatio is not equal to 1 (ie Retina displays).