Skip to content Skip to sidebar Skip to footer

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 absolute lineto() 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:

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);

}

enter image description here


Post a Comment for "Need Help In Printing Fractal Tree"