Canvas Animation
requestAnimationFrame() schedules a callback before the next screen repaint, producing smooth 60fps animations. Clear the canvas and redraw everything each frame.
requestAnimationFrame() schedules a callback before the next screen repaint, producing smooth 60fps animations. Clear the canvas and redraw everything each frame.
const ctx = canvas.getContext("2d");
let x = 0;
let animId;
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "#007bff";
ctx.beginPath();
ctx.arc(x, 100, 30, 0, Math.PI * 2);
ctx.fill();
x = (x + 2) % canvas.width;
animId = requestAnimationFrame(animate);
}
animate(); // Start
// cancelAnimationFrame(animId); // Stop
Store the requestAnimationFrame ID and call cancelAnimationFrame() to stop animations when the element is removed.