Animate a Sine Curve on HTML Canvas

This demo draws a sine curve progressively so you can see how each calculated point extends the current Canvas path. It uses requestAnimationFrame() instead of string-based setTimeout().

Your browser does not support Canvas.

Animate one section at a time Top ↑

function step() {
  angle += 1;
  const y = centerY - amplitude * Math.sin(angle * Math.PI / 180);
  ctx.lineTo(x, y);
  ctx.stroke();
  requestAnimationFrame(step);
}

requestAnimationFrame() schedules drawing with the browser's rendering cycle. For teaching slow motion, you can intentionally advance only a few points per frame.

Restart safely Top ↑

cancelAnimationFrame(animationId);
ctx.clearRect(0, 0, canvas.width, canvas.height);
angle = 0;
animationId = requestAnimationFrame(step);

Sine curve basics | Cosine curve | Sine and cosine | Slow sine and cosine

Frequently asked questions Top ↑

Why replace setTimeout() strings?

Passing functions directly is clearer and avoids evaluating code from strings.

Why use requestAnimationFrame()?

It coordinates animation work with browser painting.

How do I slow the curve further?

Advance fewer points per frame or gate updates using the frame timestamp.

Why call clearRect() on restart?

Canvas retains previously drawn pixels.

Can the same approach animate cosine?

Yes. Replace Math.sin() with Math.cos().

Canvas reference | moveTo()





plus2net.com










✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer