Created
August 15, 2017 04:17
-
-
Save jcgregorio/523da36281c6fb7d97890596e5304569 to your computer and use it in GitHub Desktop.
JS for the main page.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let dup = (o) => JSON.parse(JSON.stringify(o)); | |
let canvas = document.querySelector("canvas"), | |
ctx = canvas.getContext("2d"), | |
width = canvas.width, | |
height = canvas.height; | |
let rules = { | |
"X": "F-[[X]+X]+F[+FX]-X", | |
"F": "FF", | |
"+": "+", | |
"-": "-", | |
"[": "[", | |
"]": "]", | |
} | |
let E = (s) => s ? (rules[s[0]] + E(s.substr(1))) : ""; | |
let L = E(E(E(E(E("X"))))); | |
function draw(x, y, len, angle) { | |
let p = { x: x, y: y, a: 3 }; | |
let stack = []; | |
ctx.beginPath() | |
ctx.moveTo(p.x, p.y) | |
L.split("").forEach(function(ch) { | |
if (ch == "F") { | |
p.x += len*Math.sin(p.a); | |
p.y += len*Math.cos(p.a); | |
ctx.lineTo(p.x, p.y); | |
ctx.stroke(); | |
} else if (ch == "-") { | |
p.a += angle; | |
} else if (ch == "+") { | |
p.a -= angle; | |
} else if (ch == "[") { | |
stack.push(dup(p)); | |
} else if (ch == "]") { | |
p = stack.pop(); | |
ctx.beginPath(); | |
ctx.moveTo(p.x, p.y); | |
} | |
}) | |
} | |
function render(state) { | |
ctx.clearRect(0, 0, width, height); | |
draw(width/2, height, state.length, state.angle); | |
} | |
// Setup the Redux state store. | |
let defaultState = { | |
length: 7, | |
angle: 0.4, | |
}; | |
let updateState = (state = defaultState, action) => { | |
if (action.type == "REPLACE_ALL") { | |
state = dup(action.value); | |
} | |
return state; | |
}; | |
let store = Redux.createStore(updateState); | |
let dispatch = state => store.dispatch({type: "REPLACE_ALL", value: state}); | |
// Bind state to elements. | |
let binder = new StateTools.Binder(store, dispatch); | |
binder.add("length", "#length", {attr: "value"}, {event: "input", proc: e => +e.target.value}); | |
binder.add("angle", "#angle", {attr: "value"}, {event: "input", proc: e => +e.target.value}); | |
binder.add("length", "#lengthDisplay", {attr: "innerText"}); | |
binder.add("angle", "#angleDisplay", {attr: "innerText"}); | |
binder.add("", "canvas", render); | |
// Hook up urlReflector. | |
StateTools.urlReflector(store, dispatch); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment