Easy Canvas Resize
const canvas = document.body.appendChild(
document.createElement('canvas')
);
const c = canvas.getContext('2d');
function resize() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
draw();
}
function draw() {
c.clearRect(0, 0, canvas.width, canvas.height);
c.fillStyle = 'red';
// 30% width and height
c.fillRect(30, 30,
window.innerWidth * .3,
window.innerHeight * .3);
}
resize();
window.addEventListener('resize', resize);
Resizing a canvas is unusual, because setting the width/height
of a canvas completely erases it.
If your canvas isn’t animating, you can just redraw after resizing. Depending on what you’re drawing, working in percentages instead of pixel values can make things easier.
If you hit the “Try it out…” button, go into fullscreen and resize your browser window you’ll see things in action.