Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <html>
- <body>
- <canvas width=500 height=500 id="canvas"></canvas>
- <script>
- var context = document.getElementById('canvas').getContext('2d');
- var turtle = {
- x: 0,
- y: 0,
- angle: 0,
- stack: [],
- penDown: () => { context.beginPath(); },
- penUp: () => { context.stroke(); context.closePath(); },
- moveTo: (x,y) => { turtle.x = x; turtle.y = y; context.moveTo(x,y); },
- moveForward: (d) => { turtle.moveTo(turtle.x + d*Math.cos(turtle.angle), turtle.y + d*Math.sin(turtle.angle)); },
- lineTo: (x,y) => { turtle.angle = Math.atan2(y - turtle.y, x - turtle.x); turtle.x = x; turtle.y = y; context.lineTo(x,y); },
- lineForward: (d) => { turtle.lineTo(turtle.x + d*Math.cos(turtle.angle), turtle.y + d*Math.sin(turtle.angle)); },
- rotate: (a) => { turtle.angle += a; },
- rotateDegrees: (a) => { turtle.angle += a/180*Math.PI; },
- setAngle: (a) => { turtle.angle = a; },
- setAngleDegrees: (a) => { turtle.angle = a/180*Math.PI; },
- push: () => { turtle.stack.push({x: turtle.x, y: turtle.y, angle: turtle.angle}); },
- pop: () => { var s = turtle.stack.pop(); turtle.moveTo(s.x, s.y); turtle.angle = s.angle; },
- }
- function lindenmayer(axiom, rules, iterations) {
- if (iterations == 0) {
- return axiom
- }
- return lindenmayer(axiom.split('').map(x => {
- return (x in rules) ? rules[x] : x;
- }).join(''), rules, iterations - 1);
- }
- function draw(shape, commands) {
- shape.split('').forEach(x => commands[x]());
- }
- var axiom = '0';
- var rules = {
- '1': '11',
- '0': '1[0]0',
- };
- var iterations = 6;
- var shape = lindenmayer(axiom, rules, iterations);
- var commands = {
- '0': () => turtle.lineForward(5),
- '1': () => turtle.lineForward(5),
- '[': () => { turtle.push(); turtle.rotateDegrees(45); },
- ']': () => { turtle.pop(); turtle.rotateDegrees(-45); },
- }
- turtle.penDown();
- turtle.moveTo(0, 250);
- draw(shape, commands);
- turtle.penUp();
- console.log(shape);
- </script>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement