gengns ES

An entry from the gengns log, written by Génesis García Morilla · · HTML5, JavaScript

Resize HTML5 Canvas without losing drawing

There are multiple ways to resize a canvas without losing its content. One of the easiest way is to save its data.

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)
}

HTML

<canvas></canvas>

CSS

canvas {
  position: absolute;
  inset: 0;
  background: grey;
}
Open in JSFiddle

Tags: canvas