PutImageData()未绘制ImageData

时间:2019-05-28 09:26:56

标签: javascript canvas imagedata

我想制作一个使用这种方法的分形生成器:https://www.johndcook.com/blog/2017/07/08/the-chaos-game-and-the-sierpinski-triangle/ 这真的很有趣,我想在正方形和五边形等上尝试。 以下代码的结果应看起来像一个Sierpinski三角形,但不幸的是,画布仍为空白:/

感谢您的帮助:)

<!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 个答案:

答案 0 :(得分:1)

  

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

不是,不是-RGBA值的A分量也必须在0到255之间,并且255与CSS中的opacity: 1匹配。

1中,您给像素的不透明度为1/255,实际上只有0.00392156862

您要在此处使用255来获得全黑像素。