Sine and Cosine Curves on HTML Canvas

Sine and cosine can be plotted on the same Canvas by using the same x coordinates and scale while calculating separate y values with Math.sin() and Math.cos().

Your browser does not support Canvas.

Sine    Cosine

Calculate both y values Top ↑

const radians = angle * Math.PI / 180;
const sineY = centerY - amplitude * Math.sin(radians);
const cosineY = centerY - amplitude * Math.cos(radians);

One Canvas needs only one 2D context Top ↑

The legacy example requested the same 2D context twice and stored it in two variables. That is unnecessary. Use one context and start a new path for each curve.

function plot(fn, color) {
  ctx.beginPath();
  // add points with moveTo() and lineTo()
  ctx.strokeStyle = color;
  ctx.stroke();
}
plot(Math.sin, '#1565c0');
plot(Math.cos, '#c62828');

Sine | Slow sine | Cosine | Slow sine and cosine

Accessibility Top ↑

Use text labels for each curve and avoid relying only on different colors to distinguish them.

Frequently asked questions Top ↑

Do sine and cosine need separate contexts?

No. One CanvasRenderingContext2D is enough.

What is their phase difference?

Cosine leads sine by 90 degrees.

Why use beginPath() for each curve?

It prevents a later stroke from repainting previous path segments with the new style.

Can both curves use the same scale?

Yes because both have a natural range of -1 to 1.

Can I animate them?

Yes. See the slow-motion version.

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