Search code examples
javascriptfractalsaffinetransform

Fractal starting figure


Got computer graphic assignment to draw a fractal using webgl and affine transformations.

I can not figure out what figure I should draw in drawFigure() function or did I even took the right approach to problem.

So far this is I all managed to do:

    var canvas = document.getElementById("fractal")
        , ctx = canvas.getContext("2d")
        , depth =  6
        , HEIGHT = canvas.height
        , WIDTH = canvas.width;


    function drawFigure(color) {
        ctx.beginPath();
        ctx.fillStyle = color;   
        ctx.fillRect(WIDTH * 0.25, HEIGHT * 0.25, WIDTH * 0.5, HEIGHT * 0.5);
        ctx.fill();   
    }

    function drawFractal(depth, color, k) {
        if (depth == 0) {
            drawFigure(color);    
            return;
        }

        k = k || 1;

        // NW
        ctx.save();
        ctx.transform(0.5, 0, 0, 0.5, 0, 0);
        drawFractal(depth - 1, color  || "#FF0000", k * (-1));
        ctx.restore();

        // NE
        ctx.save();
        ctx.transform(0.5, 0, 0, 0.5, WIDTH / 2, 0);
        drawFractal(depth - 1, color  || "#00FF00", k);
        ctx.restore();

        // SW
        ctx.save();
        ctx.transform(0.5, 0, 0, 0.5, 0, HEIGHT / 2);
        drawFractal(depth - 1, color  || "#0000FF", k);
        ctx.restore();

        // SE   
        ctx.save();
        ctx.transform(-0.25 * k, 0, 0, 0.25 * k, 0.75 * WIDTH, 0.75 * HEIGHT);
        drawFractal(depth - 1, color || "#FF00FF", k);
        ctx.restore();
    }

    drawFractal(depth);
<canvas width="600" height="600" id="fractal"></canvas>	

The goal is to make fractal that looks like this:

fractal goal


Solution

  • I managed to figure it out myself. All I needed to do is to flip figure when k < 0. Achieved it by changing:

    if (depth == 0) {
        drawFigure(color);
        return;
    }
    

    to

    if (depth == 0) {
        if (k < 0) {
            ctx.translate(WIDTH, HEIGHT);
            ctx.scale(-1, -1);
        }
        drawFigure(color);
        return;
    }