xxxxxxxxxx
101
// Define the size of the Aapplication canvas and the turtle graphic
const CVS_WIDTH = 440, CVS_HEIGHT = 520;
const TG_WIDTH = 400, TG_HEIGHT = 400;
// Define the display position that corresponds to center of the turtle graphic
let cx = 220, cy = 250;
// The turtle will be created in setup
let turtle;
// Get a reference to the canvas's 2D drawing context in setup
let dc;
// ==========================================================================
// Add variables specific to this sketch
const phi = 1.6180340; // golden ratio
const hsr = 1.3247179; // Harriss spiral ratio
const pi = Math.PI;
let nbrTasks;
function setup() {
createCanvas(CVS_WIDTH, CVS_HEIGHT);
cursor(CROSS);
dc = drawingContext;
turtle = TG.getTurtle(TG_WIDTH, TG_HEIGHT);
initTurtle(turtle);
}
// Add tasks for this turtle to perform - then start it going
function initTurtle(t) {
t.turtle(csrBALL(10, "transparent", 2, "green"))
.xy(-20, 160)
.face(315)
.speed(240, 14400)
.pencolor("rgb(128 0 128)");
to_harriss(t, 220, 2.5, LT);
nbrTasks = t.nbrTasks;
t.start().ht();
}
function to_curve(t, length, dir) {
let len = (Math.sqrt(2) * length) / 2;
let rgb = `rgb(${220 - len} 0 ${128 - len / 3})`;
let ps = Math.max(length / 15, 1);
t.pensize(ps).pencolor(rgb)
.oval(len, len * 0.2, 90, dir)
.lt(180);
}
function to_harriss(t, length, limit, dir) {
if (length > limit) {
to_curve(t, length, dir);
t.push_pen();
to_harriss(t, length / 2.325, limit, LT);
t.pop_pen(POS).lt(180);
to_harriss(t, length / hsr, limit, LT);
t.rt(90);
}
}
function draw() {
background("skyblue");
drawTGframe();
turtle.draw(dc, cx, cy);
drawLegend();
}
// Draw a picture frame to display the turtle graphic
function drawTGframe() {
push();
fill(255);
stroke(0);
strokeWeight(3);
rectMode(CENTER);
rect(cx, cy, TG_WIDTH, TG_HEIGHT);
pop();
}
// Draw a legend stating any keyborad interactions
function drawLegend() {
push();
textSize(15); textAlign(CENTER, CENTER);
fill(0); noStroke(); rectMode(CORNER);
text(`Turtle will perform ${nbrTasks} tasks to complete the full spiral`, 0, 26, CVS_WIDTH, 20);
textSize(16);
text("Harriss Spiral drawn using Turtle Graphics", 0, 4, CVS_WIDTH, 20);
translate(0, cy + 10 + TG_HEIGHT / 2);
text("CONTROL KEYS", 0, 0, width, 20);
text("[B] Pause :: [N] Resume animation", 0, 20, width, 20);
pop();
}
// Keyboard interations
function keyTyped() {
switch (key) {
case "n":
turtle.start();
break;
case "b":
turtle.stop();
break;
}
}