Advertisement
Guest User

Untitled

a guest
Aug 16th, 2017
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.86 KB | None | 0 0
  1. <html>
  2. <body>
  3. <canvas width=500 height=500 id="canvas"></canvas>
  4. <script>
  5.  
  6. var context = document.getElementById('canvas').getContext('2d');
  7. var turtle = {
  8. x: 0,
  9. y: 0,
  10. angle: 0,
  11. stack: [],
  12. penDown: () => { context.beginPath(); },
  13. penUp: () => { context.stroke(); context.closePath(); },
  14. moveTo: (x,y) => { turtle.x = x; turtle.y = y; context.moveTo(x,y); },
  15. moveForward: (d) => { turtle.moveTo(turtle.x + d*Math.cos(turtle.angle), turtle.y + d*Math.sin(turtle.angle)); },
  16. lineTo: (x,y) => { turtle.angle = Math.atan2(y - turtle.y, x - turtle.x); turtle.x = x; turtle.y = y; context.lineTo(x,y); },
  17. lineForward: (d) => { turtle.lineTo(turtle.x + d*Math.cos(turtle.angle), turtle.y + d*Math.sin(turtle.angle)); },
  18. rotate: (a) => { turtle.angle += a; },
  19. rotateDegrees: (a) => { turtle.angle += a/180*Math.PI; },
  20. setAngle: (a) => { turtle.angle = a; },
  21. setAngleDegrees: (a) => { turtle.angle = a/180*Math.PI; },
  22. push: () => { turtle.stack.push({x: turtle.x, y: turtle.y, angle: turtle.angle}); },
  23. pop: () => { var s = turtle.stack.pop(); turtle.moveTo(s.x, s.y); turtle.angle = s.angle; },
  24. }
  25.  
  26. function lindenmayer(axiom, rules, iterations) {
  27. if (iterations == 0) {
  28. return axiom
  29. }
  30. return lindenmayer(axiom.split('').map(x => {
  31. return (x in rules) ? rules[x] : x;
  32. }).join(''), rules, iterations - 1);
  33. }
  34.  
  35. function draw(shape, commands) {
  36. shape.split('').forEach(x => commands[x]());
  37. }
  38.  
  39. var axiom = '0';
  40. var rules = {
  41. '1': '11',
  42. '0': '1[0]0',
  43. };
  44. var iterations = 6;
  45. var shape = lindenmayer(axiom, rules, iterations);
  46.  
  47. var commands = {
  48. '0': () => turtle.lineForward(5),
  49. '1': () => turtle.lineForward(5),
  50. '[': () => { turtle.push(); turtle.rotateDegrees(45); },
  51. ']': () => { turtle.pop(); turtle.rotateDegrees(-45); },
  52. }
  53.  
  54. turtle.penDown();
  55. turtle.moveTo(0, 250);
  56. draw(shape, commands);
  57. turtle.penUp();
  58.  
  59. console.log(shape);
  60. </script>
  61. </body>
  62. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement