Sweet spirals
To draw a spiral in SVG the <path> element opens a way with the often mysterious arc command and the “A” character.
<path d="M 0 0 a 2 2 0 0 0 4 0 a 4 4 0 0 0 -8 0 a 6 6 0 0 0 12 0" /> Starting from a specific point, draw a semicircle in one direction, reverse the trend while doubling the length of the arc. Repeat the exercise and as you connect the points with the ever expanding shape, you compose a first, convincing sketch.
The result is solid, but with the assistance of JavaScript we can go further. The logic relies on polar coordinates, a concept you might have put already to use to draw a circle as a series of connected points. In a few words, you have an angle and a radius.
let angle = 0;
let radius = 10; Increase the angle and compute the x, y coordinates with two specific trigonometric functions.
const x = Math.cos(angle) * radius;
const y = Math.sin(angle) * radius; Just remember that cosine and sine work with radians, and not degrees. With this in mind you can increase the angle with a whole integer and convert the measure to the fitting 0 to PI*2 range. Or, change the value with a much smaller increment.
for (let i = 0; i < length; i++) {
angle += 0.15;
// ...x & y
} Either way, as you increase the angle you “walk” around the center and find the position of a few points, scattered on the outline of a perfect circle.
For a spiral, the trick is simple enough to digest. Instead of a fixed offset, have the radius increase as well.
let angle = 0;
let radius = 0;
for (let i = 0; i < length; i++) {
angle += 0.15;
radius += 0.1;
// ...x & y
} Starting from 0, the first point sits in the very center. Every successive dot is pushed further and further away. Away and around the shared origin. Connect the values and gradually you have it, a new spiral.
The feature is quite notable, but as the spiral keeps growing, as the distance between the points increases, you do notice an issue. You don’t really have a series of curves, but a sequence of straight segments, linked to one another.
The point stands: increase the angle and the radius to find the coordinates of a spiral. A spiral you can draw with canvas or SVG in 2D. With the blessing of JavaScript, however, you can take the concept really further, and in higher dimensions.
Libraries like Zdog help to draw shapes on a third axis.
new Zdog.Shape({
addTo: illustration,
path: [
{ x: 0, y: 0, z: 0 },
{ x: 0.1, y: 0.01, z: 0.1 }
]
}); In the context of the spiral, this means we are able to explore the additional axis as well.
Increase the angle to rotate around the center. Increase the radius to expand in familiar arcs. Increase the z coordinate to change the depth.
Rotate the graphic around the available axes and the spiral is realized anew with a remarkable swirl.
Be it with SVG, JavaScript, JavaScript and friends you have the ingredients to craft more shapes. You have a way to whip up more complex, sweet figures.