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.
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.
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
No. It expects radians.
From -1 to 1.
It scales the mathematical result to a visible pixel height.
The curves have the same shape but are phase-shifted by 90 degrees.
Yes. Continue increasing the input angle beyond 360 degrees.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.