Animate Sine and Cosine on HTML Canvas

This demo draws sine and cosine progressively on the same Canvas. It uses one 2D context and requestAnimationFrame(), avoiding the older jQuery and string-based timeout pattern.

Your browser does not support Canvas.

Animate both series Top ↑

const sineY = centerY - amplitude * Math.sin(radians);
const cosineY = centerY - amplitude * Math.cos(radians);
requestAnimationFrame(step);

Each frame extends both curves by a few points. Keeping the two previous points separately lets each line continue from its own last position.

Cancel before restarting Top ↑

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

The original page also linked to a separate source-code demo; that link is preserved.

Sine | Slow sine | Cosine | Sine and cosine

Frequently asked questions Top ↑

Why use requestAnimationFrame()?

It is designed for visual updates synchronized with browser rendering.

Why not use two Canvas contexts?

Calling getContext('2d') twice on the same Canvas does not create two independent drawing surfaces.

How can I slow the animation?

Advance fewer points per frame or use the frame timestamp to limit update frequency.

Why cancel before restart?

Otherwise multiple animation loops can run at once.

Can I pause instead of restart?

Yes. Stop requesting new frames and keep the current angle value.

JavaScript trigonometry | moveTo() | Canvas reference





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