How to Draw a Spiral with JavaScript
In this tutorial, we’ll explore how to draw a spiral using JavaScript and the HTML5 <canvas> element. We’ll break down the code and concepts, making it easy for beginners to follow along.
For those who want to jump right in and play with a finished product, check out this online spiral maker.
Setting up the Canvas
First, we need an HTML file with a <canvas> element. This is where our spiral will be drawn.
<!DOCTYPE html>
<html>
<head>
<title>JS Spiral</title>
</head>
<body>
<canvas id="spiral-canvas"></canvas>
<script src="spiral.js"></script>
</body>
</html>
The JavaScript Logic
Now, let’s dive into the JavaScript. The core idea is to draw a series of lines that rotate and expand from the center.
1. Getting the Canvas and Context
We start by getting a reference to our canvas and its 2D drawing context.
const canvas = document.getElementById('spiral-canvas');
const ctx = canvas.getContext('2d');
2. The Drawing Function
We’ll create a function that takes parameters like sides, size, gap, and color.
function drawSpiral(sides, size, gap, color) {
// Set canvas dimensions
canvas.width = size;
canvas.height = size;
// Clear the canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Move to the center
ctx.save();
ctx.translate(canvas.width / 2, canvas.height / 2);
ctx.beginPath();
ctx.strokeStyle = color;
ctx.lineWidth = 2;
let angle = 0;
let currentGap = 0;
for (let i = 0; i < 5000; i++) {
if (sides > 1) {
angle = (2 * Math.PI / sides) * Math.floor(i / (sides * 2));
} else {
angle += 0.1;
}
currentGap += gap / 100;
const x = Math.cos(angle) * currentGap;
const y = Math.sin(angle) * currentGap;
ctx.lineTo(x, y);
}
ctx.stroke();
ctx.restore();
}
Breaking Down drawSpiral
-
canvas.width = size;andcanvas.height = size;: We set the canvas dimensions based on the desiredsize. -
ctx.translate(...): This moves the drawing origin to the center of the canvas, so our spiral starts from the middle. - The Loop: The
forloop is where the magic happens. In each iteration:- We calculate the
angleto determine the direction of the line. Ifsidesare specified, it creates a polygonal spiral. - We increment
currentGapto make the spiral expand outwards. -
Math.cos(angle)andMath.sin(angle)are used to get thexandycoordinates on a circle. -
ctx.lineTo(x, y)draws a line to the new point.
- We calculate the
-
ctx.stroke(): This actually draws the spiral on the canvas.
3. Drawing the Initial Spiral
To see our spiral, we need to call the drawSpiral function with some initial values.
drawSpiral(0, 400, 10, '#000000');
This will draw a simple, round spiral.
Interactivity (Optional)
The spiral maker example includes sliders to change the spiral’s properties in real-time. This is done by adding event listeners to the input elements and redrawing the spiral whenever a value changes.
const sizeSlider = document.getElementById('size');
sizeSlider.addEventListener('input', () => {
// Redraw the spiral with the new size
drawSpiral(0, parseInt(sizeSlider.value), 10, '#000000');
});
Conclusion
And that’s it! You’ve learned the basics of drawing a spiral with JavaScript. You can expand on this by adding more controls, colors, and even animations.
For a more advanced and feature-rich example, be sure to check out the Spiral Maker on my blog.
Happy coding!
…what’s next?
Spiral Text Generator: If you want to write text on the spiral path, use this spiral text generator online free.