Digital Spirograph

This code is meant to represent a spirograph with 3 wheels. For each wheel you can control the radius and the number of steps that the wheel takes to complete a revolution.

Log in to post a comment.

// You can find the Turtle API reference here: https://turtletoy.net/syntax
Canvas.setpenopacity(1);

// Global code will be evaluated once.
const turtle = new Turtle();
const r1 = 32 // min = 1 max = 50 step = 0.1
const r2 = 3 // min = 1 max = 50 step = 0.1
const r3 = 50 // min = 1 max = 50 step = 0.1
const s1 = 30 // min = 1 max = 500 step = 1
const s2 = 140 // min = 1 max = 500 step = 1
const s3 = 75 // min = 1 max = 500 step = 1
const steps = 1000 // min = 1 max = 2000 step = 1
turtle.penup();

class CircleDrawer {
    constructor(cx, cy, r, theta, steps) {
        this.cx = cx;
        this.cy = cy;
        this.r = r;
        this.theta = theta; //radians
        this.steps = steps;
    }
    
    getCurrentX() {
        return this.cx + Math.cos(this.theta) * this.r;
    }
    
    getCurrentY() {
        return this.cy + Math.sin(this.theta) * this.r;
    }
    
    step() {
        this.theta += Math.PI * 2 / this.steps;
    }
}

let cd = new CircleDrawer(0, 0, r1, 1, s1);
let cd2 = new CircleDrawer(0, 0, r2, 0, s2);
let cd3 = new CircleDrawer(0, 0, r3, 0, s3);
for(let i = 0; i < steps; i++) {
    turtle.goto(cd.getCurrentX() + cd2.getCurrentX() + cd3.getCurrentX(), cd.getCurrentY() + cd2.getCurrentX() + cd3.getCurrentX());
    if(i == 0) {
        turtle.pendown();
    }
    cd.step();
    cd2.step();
    cd3.step();
}