Skip to content

Instantly share code, notes, and snippets.

@conundrumer
Created August 7, 2018 01:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save conundrumer/35e9d050b1719c710288b9159629aa5f to your computer and use it in GitHub Desktop.
Save conundrumer/35e9d050b1719c710288b9159629aa5f to your computer and use it in GitHub Desktop.
generate a dragon curve
function* dragonCurveGen(startPoint, endPoint, maxIterations, left) {
const M = {
mult: (m, v) => [
m[0][0] * v[0] + m[0][1] * v[1],
m[1][0] * v[0] + m[1][1] * v[1]
],
minus: (u, v) => [u[0] - v[0], u[1] - v[1]],
plus: (u, v) => [u[0] + v[0], u[1] + v[1]],
left: [[0.5, -0.5], [0.5, 0.5]],
right: [[0.5, 0.5], [-0.5, 0.5]]
};
function* recurse(p0, p2, iterations) {
if (iterations <= 1) {
yield [p0, p2];
} else {
var p1 = M.plus(p0, M.mult(left ? M.left : M.right, M.minus(p2, p0)));
yield* recurse(p1, p0, iterations - 1);
yield* recurse(p1, p2, iterations - 1);
}
}
yield* recurse(startPoint, endPoint, maxIterations);
}
function drawLines(lines) {
for (let [[x1, y1], [x2, y2]] of lines) {
window.addLine(x1, y1, x2, y2, 2);
}
window.store.dispatch({ type: "COMMIT_TRACK_CHANGES" });
}
async function drawLinesProgressively(lines) {
const frame = () => new Promise(resolve => requestAnimationFrame(resolve));
for (let [[x1, y1], [x2, y2]] of lines) {
window.addLine(x1, y1, x2, y2, 2);
await frame();
}
window.store.dispatch({ type: "COMMIT_TRACK_CHANGES" });
}
drawLines(dragonCurveGen([0, 0], [200, 200], 12, false));
// use drawLinesProgressively to draw the lines progressively over time
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment