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:
See Question&Answers more detail:os