Canvas How to - Remove pixel by color








Question

We would like to know how to remove pixel by color.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
window.onload=function(){<!--from w  ww  .  ja v a  2s  .  com-->
    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");
    canvas.width = canvas.height = 256;
    var colors = ['255,0,0', '0,255,0', '100,100,100', '0,0,255'];
    for(var i = 0; i < 40; i++){
        ctx.fillStyle = 'rgb(' + colors[Math.floor(Math.random()*4)] + ')';
        ctx.fillRect(4*i, 4*i, 50, 50);
     }
     var selectColor = [0,0,255];
     canvas.onclick = function(){removeColor(selectColor);}
     function removeColor(color){
        var canvasData = ctx.getImageData(0, 0, 256, 256),
        pix = canvasData.data;
        for (var i = 0, n = pix.length; i <n; i += 4) {
           if(pix[i] === color[0] && pix[i+1] === color[1] && pix[i+2] === color[2]){
              pix[i+3] = 0;   
           }
        }
        ctx.putImageData(canvasData, 0, 0);
     }
}
</script>
</head>
<body>
  <p>Click canvas below to remove blue.</p>
  <canvas id="canvas"></canvas>
</body>
</html>

The code above is rendered as follows: