Resize HTML5 Canvas without losing drawing
HTML
<canvas></canvas>
CSS
canvas {
position: absolute;
inset: 0;
background: grey;
}
JavaScript
const canvas = document.querySelector('canvas')
const ctx = canvas.getContext('2d')
ctx.fillRect(10, 10, 150, 100)
const img = ctx.getImageData(0, 0, canvas.width, canvas.height)
window.onresize = () => {
canvas.width = window.innerWidth
canvas.height = window.innerHeight
ctx.putImageData(img, 0, 0)
}