square pulse animation in javascript

Here's an example code snippet that creates a square pulse animation using Canvas and requestAnimationFrame:

index.tsx
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');

const centerX = canvas.width / 2;
const centerY = canvas.height / 2;
const maxRadius = Math.min(centerX, centerY) - 10;
let radius = maxRadius;
let growing = true;

function draw() {
  // Clear the canvas before drawing a new frame
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  
  // Draw the square with the current radius
  const x = centerX - radius;
  const y = centerY - radius;
  const width = radius * 2;
  const height = radius * 2;
  ctx.fillRect(x, y, width, height);

  // Update the radius based on whether it's growing or shrinking
  if (growing) {
    radius += 1;
    if (radius >= maxRadius) {
      growing = false;
    }
  } else {
    radius -= 1;
    if (radius <= 0) {
      growing = true;
    }
  }

  // Call the next frame of the animation
  requestAnimationFrame(draw);
}

requestAnimationFrame(draw);
926 chars
39 lines

This code creates a canvas element and uses its 2D context to draw a square with a variable radius that changes over time. The animation is achieved by calling the requestAnimationFrame method inside the draw function, which causes the function to be called again and again, creating a continuous loop of frames. The growing variable keeps track of whether the radius should be increasing or decreasing, and the maxRadius variable sets an upper limit to the size of the square.

gistlibby LogSnag