Canvas How to - Manipulate pixels in a canvas








Question

We would like to know how to manipulate pixels in a canvas.

Answer


<!--from w  w w  .  ja  v  a2  s  . c  o  m-->
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){
var ctx = canvas.getContext('2d')
var W = 450, H = 450;
canvas.width = W;
canvas.height = H;
rc = function(){
    var rb = function(){
        return Math.floor(Math.random()*255);
    };
    return 'rgb('+rb()+','+rb()+','+rb()+')';
};
for(var i = 0; i < H; i+=10){
    for(var j = 0; j < W; j+=10){
        ctx.fillStyle = rc();
        ctx.fillRect(j,i,10,10);
    }
}
var map = ctx.getImageData(0,0,W,H);
for(var i = 0; i < map.data.length; i+=4){
    map.data[i+0] = 0; // drop red
    //map.data[i+1] = 0; // drop green
    map.data[i+2] = 0; // drop blue
}
ctx.putImageData(map,0,0); // comment this out to see non-green
dl.href = canvas.toDataURL();
}//]]>  
</script>
</head>
<body>
  <a id="dl">Save Image</a>
  <br>
  <canvas id="canvas"></canvas>
</body>
</html>

The code above is rendered as follows: