Search code examples
javascripthtmltreefractals

Simple JS/html5 fractal tree with decrementing line width


I would like to make a very simple fractal tree (for learning purposes) using JS. I have been using the following code which i got from a wikipedia article. It is great, only i want the line width to decrement with each iteration. As you can see i tried context.lineWidth = context.lineWidth - 1, but this doesn’t work. Does anybody have any ideas about how this can be acheived?

var elem = document.getElementById('canvas');
var context = elem.getContext('2d');

context.fillStyle = '#000';
context.lineWidth = 20;

var deg_to_rad = Math.PI / 180.0;
var depth = 9;

function drawLine(x1, y1, x2, y2){
context.moveTo(x1, y1);
context.lineTo(x2, y2);
context.lineWidth = context.lineWidth - 1;
}
function drawTree(x1, y1, angle, depth){
if (depth != 0){
    var x2 = x1 + (Math.cos(angle * deg_to_rad) * depth * 10.0);
    var y2 = y1 + (Math.sin(angle * deg_to_rad) * depth * 10.0);
    drawLine(x1, y1, x2, y2);
    drawTree(x2, y2, angle - 20, depth - 1);
    drawTree(x2, y2, angle + 20, depth - 1);
    }

}
context.beginPath();
drawTree(300, 500, -90, depth);
context.closePath();
context.stroke();

It would also be great if there was a way to do this in stages so that when i click on a button it adds a new branch. Anyway, your advice would be greatly appreciated.


Solution

  • I have created and tweaked a fiddle which somehow does what you want.

    fiddle

    All in all: You need to stroke each time a new line width is set. So the code looks like this:

    function drawLine(x1, y1, x2, y2, lw){
        context.beginPath();
        context.moveTo(x1, y1);
        context.lineTo(x2, y2);
        context.lineWidth = lw;
        context.closePath();
        context.stroke();
    }
    
    function drawTree(x1, y1, angle, depth, lw){
    if (depth != 0){
        var x2 = x1 + (Math.cos(angle * deg_to_rad) * depth * 10.0);
        var y2 = y1 + (Math.sin(angle * deg_to_rad) * depth * 10.0);
        drawLine(x1, y1, x2, y2, lw);
        drawTree(x2, y2, angle - 20, depth - 1, lw - 1);
        drawTree(x2, y2, angle + 20, depth - 1, lw - 1);
    }
    }
    
    drawTree(300, 500, -90, depth, depth);