76591

Need help in printing fractal tree

Question:

I need some help in printing fractal tree using JavaScript.

I have written code which prints tree sequence according to the rules defined for the tree, but having some trouble to print the tree. Thanks for all the help.

Here is the code:

var sentence = "F"; var rules = []; rules[0] = { a: "F", b: "F[+F]F[-F]F" } setup(); function setup() { turtle(); for (i = 0; i < 2; i++){ generate(); } } function turtle(){ var canvas = document.getElementById("myCanvas"); var context = canvas.getContext('2d'); for (var i = 0; i < sentence.length; i++){ context.beginPath(); var current = sentence.charAt(i); if (current == "F"){ context.stroke(); context.lineTo(50,50); }else if (current == "+"){ context.rotate(20*Math.PI/180); }else if (current == "-"){ context.rotate(-20*Math.PI/180); }else if (current == "["){ context.save(); }else if (current == "]"){ context.restore(); } } } function generate(){ var nextSentence = ""; for (var i = 0; i < sentence.length; i++){ var current = sentence.charAt(i); var found = false; for (var j = 0; j < rules.length; j++ ){ if (current == rules[j].a){ found = true; nextSentence += rules[j].b; console.log(nextSentence); break; } } if (!found){ nextSentence += current; } } sentence = nextSentence; turtle(); }

I am able to print a tree sequence, but need some help in converting that tree sequence to be able to print a tree on the canvas. The output should look something like this:

<a href="https://i.stack.imgur.com/xmBay.jpg" rel="nofollow"><img alt="enter image description here" class="b-lazy" data-src="https://i.stack.imgur.com/xmBay.jpg" data-original="https://i.stack.imgur.com/xmBay.jpg" src="https://etrip.eimg.top/images/2019/05/07/timg.gif" /></a>

Answer1:

There are some issue with your drawing logic. You code seems to be assuming that save() and restore() also save the coordinates and restore them -- they don't. You aren't using rotate() correctly (it rotates relative to the origin so you need to also translate()). You're doing <em>absolute</em> lineto() when you should be doing it <em>relative</em> to the current position. And moving in the wrong direction. And other issues.

Here's my rework of your code to make it run just enough to produce the example tree:

var sentence = "F"; var rules = []; rules[0] = { a: "F", b: "F[+F]F[-F]F" } var x = 150; // starting x var y = 400; // starting y var y_stack = []; // save & restore don't handle coordinates function turtle(sentence, context) { for (var i = 0; i < sentence.length; i++) { var current = sentence.charAt(i); if (current == "F") { y -= 35; context.lineTo(x, y); context.stroke(); } else if (current == "+") { context.translate(x, y); context.rotate(20 * Math.PI / 180); context.translate(-x, -y); } else if (current == "-") { context.translate(x, y); context.rotate(-20 * Math.PI / 180); context.translate(-x, -y); } else if (current == "[") { context.save(); y_stack.push(y); } else if (current == "]") { context.restore(); y = y_stack.pop(); context.moveTo(x, y) } } } function generate(sentence) { var nextSentence = ""; for (var i = 0; i < sentence.length; i++) { var current = sentence.charAt(i); var found = false; for (var j = 0; j < rules.length; j++ ) { if (current == rules[j].a) { found = true; nextSentence += rules[j].b; break; } } if (!found) { nextSentence += current; } } return nextSentence; } function draw() { var canvas = document.getElementById("myCanvas"); var context = canvas.getContext('2d'); context.moveTo(x, y); for (i = 0; i < 2; i++) { sentence = generate(sentence); } console.log(sentence); turtle(sentence, context); }

<a href="https://i.stack.imgur.com/AQ9jC.png" rel="nofollow"><img alt="enter image description here" class="b-lazy" data-src="https://i.stack.imgur.com/AQ9jC.png" data-original="https://i.stack.imgur.com/AQ9jC.png" src="https://etrip.eimg.top/images/2019/05/07/timg.gif" /></a>

Recommend

  • How to erase partially image with javascript and result of erase pixel is transperent?
  • Extend Line based on slope to the end of canvas/drawing area
  • p5js sketch inside wordpress page
  • Rotating a line around a circle
  • Jquery drag drop on html canvas
  • FadeIn FadeOut in Html5 canvas
  • fabricjs: _render method of my fabric.Object subclass is never called
  • How to draw the line in canvas
  • On a canvas, difference between drawImage with png vs create a drawing using strokes?
  • My div will not slideDown() when clicked.
  • HTML5 canvas drawImage not working on first click
  • Get byte[] from
  • How to Filter ListAdapter using getFilter() within a fragment
  • IndexSizeError on drawImage on IE and Edge
  • Remove previous Directions Route Google Maps
  • write text on image and show it to a imageview
  • How to draw a line dynamically in android [duplicate]
  • JPA flush vs commit
  • Elasticsearch script query involving root and nested values
  • Why use database factory in asp.net mvc?
  • How do I configure context broker accept post requests from my remote sensor?
  • Chart.js Multiple dataset
  • How do I get HTML corresponding to current DOM tree?
  • How to render a blob on a canvas element?
  • JQuery Internet Explorer and ajaxstop
  • JSON response opens as a file, but I can't access it with JavaScript
  • Why HTML5 Canvas with a larger size stretch a drawn line?
  • AES padding and writing the ciphertext to a disk file
  • Javascript Callbacks with Object constructor
  • Change an a tag attribute in JavaScript based on screen width
  • Invalid access key error using credentials redeemed from an amazon open id token
  • retrieve vertices with no linked edge in arangodb
  • PHP: When would you need the self:: keyword?
  • Acquiring multiple attributes from .xml file in c#
  • FormattedException instead of throw new Exception(string.Format(…)) in .NET
  • Change div Background jquery
  • apache spark aggregate function using min value
  • reshape alternating columns in less time and using less memory
  • Android Heatmap on canvas or ImageView
  • How can I use threading to 'tick' a timer to be accessed by other threads?