This week in the Creators group we looked at emulating the classic toy, the Spirograph.
The Spirograph consists of geared plastic discs. One disc is fixed in place over a sheet of paper and the other, with a pencil tracing the path, is allowed to spin around it. The result is a complex and beautiful design on the paper.
This diagram should help explain in conjunction with the photo. The centre of the black disc spins around the centre of the red disc, which itself doesn’t move. So the centre of the black disc rotates around in a circle. Pretty simple?
Now, the pencil itself rotates around the centre of the black disc. Shouldn’t that make a circle too? Well it would if the black disc wasn’t moving. Thankfully though, it is and that’s what makes this interesting.
Finding the Location of the “Pencil”
So how do we find the location of the pencil? Let’s look at our diagram again, but with things re-labeled a bit:
- Centre: Formerly “centre of red disc”. It’s the fixed centre of our spirograph
- Centre2: Formerly “centre of black disk”
- Point: The point on our curve. This is where the pencil would be in a physical spirograph.
- Radius0: Distance from Centre to Centre2
- Radius1:Distance from Centre2 to Point
- Angle0: The current angle of the line between Centre and Centre2
- Speed0: The amount that angle0 increases every time we draw
- Angle1: The current angle of the line between Centre2 and Point
- Speed1: The amount that angle1 increases each time we draw
So at any time the location of our point is:
Point = Centre + [Centre2 relative to Centre] + [Point relative to Centre2]
So know where Centre is and if we can calculate where Centre2 is relative to Centre and similarly where Point is relative to Centre2, we can just add them all together!
Given an angle and a distance, can we get a location?
The answer to this is a resounding “yes”! Look at the diagram:
given an angle and a radius, we can calculate the X and Y position of any point around a circle. The magic is the COS and SIN (pronounced “kos” and “sign”) functions. These functions exist in almost all programming languages and JavaScript’s no exception.
Using p5.Vector
The last big concept we tackled thus week was using P5js’s built-in vector class to store (x, y) points and make our code tidier. To make a vector we just use createVector(x, y). We can then use functions to add them together, etc. We would get the same result working with the X and Y values separately but the code is a lot neater and shorter.
And in conclusion
This looks pretty cool:
Getting this week’s code
As aways, all the code from our Creator group can be found on our GitHub repository.