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

Random Walk to Target

  1. const canvas = document.createElement('canvas');
  2. const c = canvas.getContext('2d');
  3.  
  4. let targetX, targetY, startX, startY;
  5. const rectSize = 20;
  6. const maxStep = 10;
  7.  
  8. const matchStep = maxStep / 2;
  9. const halfRectSize = rectSize / 2;
  10. let matchTime = 0;
  11. const resetTime = 20;
  12.  
  13. function randX() {
  14.   return innerWidth * 0.8 * Math.random() + innerWidth * 0.1;
  15. }
  16. function randY() {
  17.   return innerHeight * 0.8 * Math.random() + innerHeight * 0.1;
  18. }
  19.  
  20. function resize() {
  21.   canvas.width = innerWidth;
  22.   canvas.height = innerHeight;
  23.   reset();
  24. }
  25. window.addEventListener('resize', resize);
  26. resize();
  27.  
  28. document.body.appendChild(canvas);
  29. document.body.style.margin = 0;
  30.  
  31. function reset() {
  32.   matchTime = 0;
  33.   targetX = randX();
  34.   targetY = randY();
  35.   startX = randX();
  36.   startY = randY();
  37.   c.fillStyle = '#ccc';
  38.   c.fillRect(0, 0, innerWidth, innerHeight);
  39.  
  40.   c.fillStyle = '#c79500';
  41.   c.fillRect(
  42.     targetX - halfRectSize,
  43.     targetY - halfRectSize,
  44.     rectSize,
  45.     rectSize
  46.   );
  47.  
  48.   c.fillStyle = '#4e82c7';
  49.   c.fillRect(startX - halfRectSize, startY - halfRectSize, rectSize, rectSize);
  50. }
  51.  
  52. function loop() {
  53.   c.strokeStyle = 'black';
  54.   c.beginPath();
  55.   c.moveTo(startX, startY);
  56.   if (startX < targetX) {
  57.     startX += Math.random() * maxStep;
  58.   } else if (startX > targetX) {
  59.     startX -= Math.random() * maxStep;
  60.   }
  61.   if (startY < targetY) {
  62.     startY += Math.random() * maxStep;
  63.   } else if (startY > targetY) {
  64.     startY -= Math.random() * maxStep;
  65.   }
  66.  
  67.   c.lineTo(startX, startY);
  68.   c.stroke();
  69.  
  70.   if (
  71.     Math.abs(startX - targetX) < matchStep &&
  72.     Math.abs(startY - targetY) < matchStep
  73.   ) {
  74.     matchTime++;
  75.     if (matchTime > resetTime) {
  76.       reset();
  77.     }
  78.   }
  79.  
  80.   window.requestAnimationFrame(loop);
  81. }
  82. loop();

Randomly walk to a target.

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