)
}
}
)
(
}
{
)
)
(
)
(
(
{
}
)
(
)
}
)
)
{
(
(
)
)
}
)
(
}

Easy Canvas Resize

  1. const canvas = document.body.appendChild(
  2.   document.createElement('canvas')
  3. );
  4. const c = canvas.getContext('2d');
  5.  
  6. function resize() {
  7.   canvas.width = window.innerWidth;
  8.   canvas.height = window.innerHeight;
  9.   draw();
  10. }
  11.  
  12. function draw() {
  13.   c.clearRect(0, 0, canvas.width, canvas.height);
  14.   c.fillStyle = 'red';
  15.   // 30% width and height
  16.   c.fillRect(30, 30, 
  17.     window.innerWidth * .3, 
  18.     window.innerHeight * .3);
  19. }
  20.  
  21. resize();
  22. 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.

snippet.zone ~ 2021-24 /// {s/z}