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

Draw a Spiral with 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 = 'blue';
  15.  
  16.   const iter = 300,
  17.         halfWidth = window.innerWidth / 2,
  18.         halfHeight = window.innerHeight / 2;
  19.   let rad = 0, theta = 0, x, y;
  20.   for (let i = 0; i < iter; i++) {
  21.     x = halfWidth + rad * Math.cos(theta);
  22.     y = halfHeight + rad * Math.sin(theta);
  23.     c.fillRect(x, y, 5, 5);
  24.     rad += Math.min(window.innerWidth, window.innerHeight) * 0.0015;
  25.     theta += .1;
  26.   }
  27. }
  28.  
  29. resize();
  30. window.addEventListener('resize', resize);

Expanding on yesterdays post, this draws a resizable sprial on a canvas.

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.

Semi-golfed Canvas Setup

  1. ((
  2.   width = 200, height = 200, 
  3.   cnv = document.body.appendChild(
  4.     Object.assign(
  5.       document.createElement('canvas'), {
  6.       width, height
  7.     })
  8.   ),
  9.   c = cnv.getContext('2d'), 
  10.   f = c.fillRect.bind(c),
  11.   C = _ => c.fillStyle = _) => {
  12.  
  13.   C`gray`; f(0, 0, width, height);
  14.   C`blue`; f(10, 10, 100, 20);
  15. })();
snippet.zone ~ 2021-24 /// {s/z}