Cosine Curve on HTML Canvas with JavaScript

A cosine curve on Canvas is created by stepping through x positions, converting each angle from degrees to radians, calculating Math.cos(), and mapping the result from -1…1 into Canvas y coordinates.

Your browser does not support Canvas.

Cosine formula Top ↑

const radians = degrees * Math.PI / 180;
const y = centerY - amplitude * Math.cos(radians);

The subtraction is needed because Canvas y coordinates grow downward. At 0°, cosine is 1, so the first plotted point appears above the center line.

Plot the curve Top ↑

ctx.beginPath();
for (let degree = 0; degree <= 540; degree += 2) {
  const radians = degree * Math.PI / 180;
  const y = centerY - amplitude * Math.cos(radians);
  if (degree === 0) ctx.moveTo(x, y);
  else ctx.lineTo(x, y);
}
ctx.stroke();

For the JavaScript math function, see Math.sin() and trigonometric examples.

Sine curve | Slow sine drawing | Sine and cosine together | Slow sine and cosine

Frequently asked questions Top ↑

Does Math.cos() use degrees?

No. It expects radians.

What is the range of cosine?

From -1 to 1.

Why multiply by amplitude?

It scales the mathematical result to a visible pixel height.

How is cosine different from sine?

The curves have the same shape but are phase-shifted by 90 degrees.

Can I plot more than one period?

Yes. Continue increasing the input angle beyond 360 degrees.

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