Canvas How to - Set image pixel data








Question

We would like to know how to set image pixel data.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){<!--   w  w w. ja  v a 2s .  com-->
        var canvas = document.getElementById("canvas");
        var ctx = canvas.getContext("2d");
        // noise factors
        var n1 = .95;
        var n2 = .01;
        var image = ctx.getImageData(0, 0, canvas.width, canvas.height);
        var idx = 0;
        for (var y = 0; y < 128; ++y) {
            for (var x = 0; x < 128; ++x) {
                // noise
                var r = n1 + Math.random() * n2;
                var g = n1 + Math.random() * n2;
                var b = n1 + Math.random() * n2;
                image.data[idx + 0] = 128 * r;
                image.data[idx + 1] = 128 * g;
                image.data[idx + 2] = 128 * b;
                image.data[idx + 3] = Math.min(x + y,255);
                idx += 4;
            }
        }
        ctx.putImageData(image, 0, 0);
}//]]>  
</script>
</head>
<body>
  <canvas id="canvas" width=128 height=128></canvas>
</body>
</html>

The code above is rendered as follows: