draw a spiral with multiple turns in javascript

To draw a spiral with multiple turns using JavaScript, we can leverage the HTML5 canvas element. Here's an example implementation that allows you to specify the number of turns, the distance between each turn and the gap between each spiral line:

index.tsx
function drawSpiral(turns, distance, gap) {
  // get canvas element and 2d context
  const canvas = document.getElementById('canvas');
  const ctx = canvas.getContext('2d');

  // set styles
  ctx.strokeStyle = 'black';
  ctx.lineWidth = 2;

  // set starting position in centre of canvas
  let x = canvas.width / 2;
  let y = canvas.height / 2;

  // draw spiral
  ctx.beginPath();
  for (let i = 0; i < turns * 360; i++) {
    let angle = 0.1 * i;
    let radius = distance * Math.sqrt(i);

    // add gap between lines if specified
    if (gap) {
      radius += gap * i / (2 * Math.PI);
    }

    // calculate new x, y coordinates
    x = canvas.width / 2 + radius * Math.sin(angle);
    y = canvas.height / 2 + radius * Math.cos(angle);

    // move pen to new position
    ctx.lineTo(x, y);
  }

  // draw spiral
  ctx.stroke();
}
838 chars
36 lines

You can call this function with the desired number of turns, distance between each turn and gap between spiral lines (optional):

index.tsx
drawSpiral(5, 5, 1);
21 chars
2 lines

This will draw a spiral with 5 turns, a distance of 5 between each turn and a gap of 1 between each spiral line.

gistlibby LogSnag