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().
Sine Cosine
const radians = angle * Math.PI / 180;
const sineY = centerY - amplitude * Math.sin(radians);
const cosineY = centerY - amplitude * Math.cos(radians);
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
Use text labels for each curve and avoid relying only on different colors to distinguish them.
No. One CanvasRenderingContext2D is enough.
Cosine leads sine by 90 degrees.
It prevents a later stroke from repainting previous path segments with the new style.
Yes because both have a natural range of -1 to 1.
Yes. See the slow-motion version.
JavaScript trigonometry | moveTo() | Canvas reference
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.