create animation in javascript

There are different methods to create animations in JavaScript, one of them is using the HTML5 canvas element and the built-in requestAnimationFrame method.

Here is a basic example of how to animate a rectangle moving across the canvas using requestAnimationFrame:

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

let x = 0;

function animate() {
  // Clear the canvas on each frame
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // Draw the rectangle at the current position
  ctx.fillRect(x, 50, 50, 50);

  // Increment the position for the next frame
  x += 1;

  // Call the animate function again on the next frame
  window.requestAnimationFrame(animate);
}

// Start the animation
window.requestAnimationFrame(animate);
509 chars
22 lines

In this example, we create a canvas element and get its context. We also define a variable x that represents the position of the rectangle on the x-axis.

The animate function is called recursively using requestAnimationFrame. On each frame, we clear the canvas, draw the rectangle at the current position, and increment the position for the next frame. This creates the illusion of movement.

You can customize this code to create more complex animations and add other elements to the canvas.

gistlibby LogSnag