Drawing a spiral on an HTML canvas using JavaScript

Viewed 34416

I have searched and haven't found anything really on how to draw spirals in canvas using JavaScript.

I thought it might be possible to do it with the bezier curve and if that didn't work use lineTo(), but that seemed a lot harder.

Also, to do that I'm guessing I would have to use trigonometry and graphing with polar coordinates and its been a while since I did that. If that is the case could you point me in the right direction on the math.

6 Answers

The following code approximates a spiral as a collection of quarters of a circle each with a slightly larger radius. It might look worse than an Archimedes spiral for small turning numbers but it should run faster.

function drawSpiral(ctx, centerx, centery, innerRadius, outerRadius, turns=2, startAngle=0){
    ctx.save();
    ctx.translate(centerx, centery);
    ctx.rotate(startAngle);
    let r = innerRadius;
    let turns_ = Math.floor(turns*4)/4;
    let dr = (outerRadius - innerRadius)/turns_/4;
    let cx = 0, cy = 0; 
    let directionx = 0, directiony = -1;
    
    ctx.beginPath();
    let angle=0;
    for(; angle < turns_*2*Math.PI; angle += Math.PI/2){
        //draw a quarter arc around the center point (x, cy)
        ctx.arc( cx, cy, r, angle, angle + Math.PI/2);
        
        //move the center point and increase the radius so we can draw a bigger arc
        cx += directionx*dr;
        cy += directiony*dr;
        r+= dr;
        
        //rotate direction vector by 90 degrees
        [directionx, directiony] = [ - directiony, directionx ];
    }
    //draw the remainder of the last quarter turn
    ctx.arc( cx, cy, r, angle, angle + 2*Math.PI*( turns - turns_ ))
    ctx.stroke();
    ctx.restore();
}

Result:

enter image description here

Related