0

I want to make a fractal generator that uses this method: https://www.johndcook.com/blog/2017/07/08/the-chaos-game-and-the-sierpinski-triangle/ It's really interesting and I wanted to try it on squares and pentagons etc. The result of the Code below should look like a Sierpinski triangle but unfortunately the canvas stays blank :/

Thx for your help :)

<!DOCTYPE html>
<html>
    <head>
        <title>sierpinksi polygons</title>
    </head>
    <body>
        <canvas width="500" height="500" id="canvas"></canvas>
        <script>
            let canavas = document.getElementById("canvas");
            let ctx = canvas.getContext("2d");
            let imgdata = ctx.createImageData(500, 500);
            let data = imgdata.data;
            let vertices = [{x: 0, y: 0}, {x: 500, y: 0}, {x: 250, y: 433}];

            function pixel(x, y) {
                data[4*y*canvas.width+4*x + 3] = 1; //sets alpha to 1 which makes the pixel black
            }

            function random() {
                return vertices[Math.floor(Math.random()*vertices.length)];
            }

            let point = {x: 0, y: 0};

            for (let i = 0; i < 10000; i++) {
                let temp = random();

                //algorithm to draw sierpinksi triangle pixel by pixel
                point.x = point.x + (temp.x - point.x)/2;
                point.y = point.y + (temp.y - point.y)/2;
                pixel(Math.round(point.x), Math.round(point.y));
            }
            console.log(imgdata)
            ctx.putImageData(imgdata, 0, 0);
        </script>
    </body>
</html>

1 Answers1

1

data[4*y*canvas.width+4*x + 3] = 1; //sets alpha to 1 which makes the pixel black

No, it doesn’t - the A component of the RGBA value has to be in the range of 0 to 255 as well, 255 matching what opacity: 1 in CSS would mean.

With 1 you have given your pixels an opacity of 1/255 here, which is really only just 0.00392156862

You want to use 255 here to get full black pixels.

04FS
  • 5,660
  • 2
  • 10
  • 21