Need Help In Printing Fractal Tree
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 p
Solution 1:
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 absolutelineto()
when you should be doing it relative 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:
varsentence="F";
varrules= [];
rules[0] = {
a: "F",
b: "F[+F]F[-F]F"
}
varx=150; // starting xvary=400; // starting yvary_stack= []; // save & restore don't handle coordinates
function turtle(sentence, context) {
for (vari=0; i < sentence.length; i++) {
varcurrent= sentence.charAt(i);
if (current == "F") {
y -= 35;
context.lineTo(x, y);
context.stroke();
} elseif (current == "+") {
context.translate(x, y);
context.rotate(20 * Math.PI / 180);
context.translate(-x, -y);
} elseif (current == "-") {
context.translate(x, y);
context.rotate(-20 * Math.PI / 180);
context.translate(-x, -y);
} elseif (current == "[") {
context.save();
y_stack.push(y);
} elseif (current == "]") {
context.restore();
y = y_stack.pop();
context.moveTo(x, y)
}
}
}
function generate(sentence) {
varnextSentence="";
for (vari=0; i < sentence.length; i++) {
varcurrent= sentence.charAt(i);
varfound=false;
for (varj=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() {
varcanvas= document.getElementById("myCanvas");
varcontext= canvas.getContext('2d');
context.moveTo(x, y);
for (i = 0; i < 2; i++) {
sentence = generate(sentence);
}
console.log(sentence);
turtle(sentence, context);
}
Post a Comment for "Need Help In Printing Fractal Tree"