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

Wiggly Line Canvas

  1. const canvas = document.body.appendChild(
  2.   document.createElement('canvas')
  3. );
  4. const c = canvas.getContext('2d');
  5. document.body.style.margin = 0;
  6.  
  7. function resize() {
  8.   canvas.width = innerWidth;
  9.   canvas.height = innerHeight;
  10. }
  11. addEventListener('resize', resize);
  12. resize();
  13.  
  14. const PAD = 50;
  15. const RAD = 2;
  16. const SPEED = 20;
  17. const TWO_PI = Math.PI * 2;
  18.  
  19. let mode = 'draw';
  20.  
  21. let t = Math.random() * TWO_PI, 
  22.     x = innerWidth / 2, 
  23.     y = innerHeight / 2,
  24.     vx = 0, vy = 0, ta = 0;
  25.  
  26. function loop() {
  27.   for (var i = 0; i < SPEED; i++) {
  28.     t = Math.sin(ta) * TWO_PI;
  29.     vx = RAD * Math.cos(t);
  30.     vy = RAD * Math.sin(t);
  31.     ta += Math.random() * 0.1 - 0.05;
  32.     x += vx;
  33.     y += vy;
  34.  
  35.     if (Math.random() < 0.005) {
  36.       mode = 'no draw';
  37.     } else if (Math.random() < 0.005) {
  38.       mode = 'draw';
  39.     }
  40.  
  41.     if (mode === 'draw') {
  42.       c.fillStyle = 'red';
  43.       c.fillRect(x, y, 2, 2);
  44.     }
  45.  
  46.     if (x < -PAD) {
  47.       x = innerWidth + PAD;
  48.     } else if (x > innerWidth + PAD) {
  49.       x = -PAD;
  50.     }
  51.     if (y < -PAD) {
  52.       y = innerHeight + PAD;
  53.     } else if (y > innerHeight + PAD) {
  54.       y = -PAD;
  55.     }
  56.   }
  57.  
  58.   requestAnimationFrame(loop);
  59. }
  60. loop();

Recently saw this in some very old code – cool trick for moving things in a wiggly way – or in this case, drawing a wiggly line.

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