This demo draws a sine curve progressively so you can see how each calculated point extends the current Canvas path. It uses requestAnimationFrame() instead of string-based setTimeout().
function step() {
angle += 1;
const y = centerY - amplitude * Math.sin(angle * Math.PI / 180);
ctx.lineTo(x, y);
ctx.stroke();
requestAnimationFrame(step);
}
requestAnimationFrame() schedules drawing with the browser's rendering cycle. For teaching slow motion, you can intentionally advance only a few points per frame.
cancelAnimationFrame(animationId);
ctx.clearRect(0, 0, canvas.width, canvas.height);
angle = 0;
animationId = requestAnimationFrame(step);
Sine curve basics | Cosine curve | Sine and cosine | Slow sine and cosine
Passing functions directly is clearer and avoids evaluating code from strings.
It coordinates animation work with browser painting.
Advance fewer points per frame or gate updates using the frame timestamp.
Canvas retains previously drawn pixels.
Yes. Replace Math.sin() with Math.cos().
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.