draw a spiral in javascript

To draw a spiral in Javascript, we can use the canvas element and draw a series of lines using trigonometry. To animate the spiral, we can use the requestAnimationFrame() method.

Here's the code to draw a spiral:

index.tsx
// get the canvas element
var canvas = document.getElementById("myCanvas");

// set the context to 2D
var ctx = canvas.getContext("2d");

// set the starting coordinates
var x = canvas.width / 2;
var y = canvas.height / 2;

// set the radius and angle increment values
var radius = 0;
var angle = 0.05;

// set the line color and width
ctx.strokeStyle = "red";
ctx.lineWidth = 2;

// begin the path
ctx.beginPath();

// draw the spiral
for (var i = 0; i < 500; i++) {
    // calculate the next x and y coordinates
    x = canvas.width / 2 + radius * Math.cos(angle);
    y = canvas.height / 2 + radius * Math.sin(angle);

    // draw a line to the next point
    ctx.lineTo(x, y);

    // increment the radius and angle values
    radius += 0.1;
    angle += 0.1;
}

// stroke and close the path
ctx.stroke();
ctx.closePath();
827 chars
39 lines

And here's the code to animate the spiral:

index.tsx
// get the canvas element
var canvas = document.getElementById("myCanvas");

// set the context to 2D
var ctx = canvas.getContext("2d");

// set the starting coordinates
var x = canvas.width / 2;
var y = canvas.height / 2;

// set the radius and angle increment values
var radius = 0;
var angle = 0.05;

// set the line color and width
ctx.strokeStyle = "red";
ctx.lineWidth = 2;

// set the animation function
function animate() {
    // clear the canvas
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    // begin the path
    ctx.beginPath();

    // draw the spiral
    for (var i = 0; i < 500; i++) {
        // calculate the next x and y coordinates
        x = canvas.width / 2 + radius * Math.cos(angle);
        y = canvas.height / 2 + radius * Math.sin(angle);

        // draw a line to the next point
        ctx.lineTo(x, y);

        // increment the radius and angle values
        radius += 0.1;
        angle += 0.1;
    }

    // stroke and close the path
    ctx.stroke();
    ctx.closePath();

    // request the next animation frame
    requestAnimationFrame(animate);
}

// start the animation
animate();
1135 chars
51 lines

Note that in the animation code, we're using the requestAnimationFrame() method to call the animate() function repeatedly, which creates the illusion of motion.

gistlibby LogSnag