JSFiddle - React, Tailwind, and code Playground
HTML
<div id="info"></div>
JavaScript
// Turtle graphics drawing to SVG (?)
var TAU = 2 * Math.PI;
var moveCount = 0;
var pen = true;
var d = "";
var vector = {
x: 0,
y: 1
};
var currentAngle = 0;
// Relative turns, angles are 0.0 to 1.0
var turn = function(){
vector.x = Math.sin(TAU*currentAngle);
vector.y = Math.cos(TAU*currentAngle);
};
var turnRight = function(angle){
currentAngle += angle;
currentAngle = currentAngle%1;
turn();
};
var turnLeft = function(angle){
turnRight(-angle);
};
// Absolute turn
var turnTo = function(angle){
currentAngle = angle;
turn();
};
// Drawing
var penUp = function(){
pen = false;
};
var penDown = function(){
pen = true;
};
// Relative moves
var moveForward = function (distance) {
d += pen ? "l " : "m ";
d += (distance * vector.x) + " " + (distance * vector.y) + " ";
moveCount++;
}
// Absolute moves
var moveTo = function (x, y) {
d += pen ? "L " : "M ";
d += x + " " + y + " ";
moveCount++;
}
// Swiss Cross (recursive space-filling curve algorithm)
var segmentLength = 10;
function unit(iteration) {
if (iteration > 0) {
unit(iteration - 1);
turnRight(0.25);
unit(iteration - 1);
moveForward(segmentLength);
unit(iteration - 1);
turnRight(0.25);
unit(iteration - 1);
}
}
// Draw it
penUp();
moveTo(20, 30);
turnTo(9);
penDown();
// Top half
unit(6);
// Bottom half
moveForward(segmentLength);
unit(6);
// var doc = document.getElementById("doc");
// var path = doc.getElementById("turtle");
// path.setAttributeNS(null, "d", d);
// Show moves count
var info = document.createElement("div");
info.innerHTML = moveCount + " moves ";
document.body.appendChild(info);
// Make SVG Blob
window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL || null;
var svgString = '<svg id="doc" xmlns="http://www.w3.org/2000/svg" version="1.1" width="500" height="500"><path id="turtle" d="';
svgString += d;
svgString += '" stroke="black" fill="none" vector-effect="non-scaling-stroke" /></svg>';
var...