3

I'm trying to find if a pixel is black or not on a canvas

    var check = function(player,keyPressed) {
//series of ifs to determine what pixel to check. 
    }

I would need to return either true or false if the pixel is false, I've tried getImageData but I wasn't able to figure out how to use it properly.

MickDom
  • 157
  • 2
  • 12
  • Take a look to this questions: http://stackoverflow.com/questions/6735470/get-pixel-color-from-canvas-on-mouseover http://stackoverflow.com/questions/667045/getpixel-from-html-canvas – ADreNaLiNe-DJ Apr 27 '16 at 13:43
  • 1
    getImageData is an array of the pixels, 4 bytes for every pixel (r, g, b, a). You can simply loop through its pixels, or identify which one you need from the x, y co-ords and interrogate it for 0 in the first three values. – ManoDestra Apr 27 '16 at 13:44

1 Answers1

6
var canvas= document.getElementById('myCanv');
var pixelData = canvas.getContext('2d').getImageData(event.clientX, event.clientY, 1, 1).data;

That is it !!

Of course, Assuming that , you have :

   <canvas id="myCanv"></canvas> 

FIDDLE

Then :

function isBlack(dataPixel){
   if(dataPixel[0]==dataPixel[1] && dataPixel[1]==dataPixel[2] && dataPixel[2]===0 ){
      return true
   }
}

http://jsfiddle.net/abdennour/4kdLfooj/11/

Abdennour TOUMI
  • 87,526
  • 38
  • 249
  • 254
  • 1
    Then I just check the values in the pixelData array to see if they're right for color black? – MickDom Apr 27 '16 at 13:46
  • 3
    Of course, he'll still need to interrogate the data returned to check that it's black. – ManoDestra Apr 27 '16 at 13:46
  • Just in case you had problems with mouse coordinates on the canvas, here's my answer: http://stackoverflow.com/a/27204937/607407 – Tomáš Zato Apr 27 '16 at 14:43
  • 1
    Btw why not just `dataPixel[0]+dataPixel[1]+dataPixel[2]==0`? – Tomáš Zato Apr 27 '16 at 14:44
  • 2
    I like @TomášZato's simplification, but you must also check the alpha element (dataPixel[3]). If the alpha is zero, then that pixel is transparent -- not black. ;-) `dataPixel[0]+dataPixel[1]+dataPixel[2]+dataPixel[3]==0` – markE Apr 27 '16 at 17:45
  • Be careful with comparison of color to exact (0, 0, 0). Sometimes because of compression, transformations or specifics of canvas rendering pixels at the color border may become impure, so instead of rgb being (0, 0, 0) it may be something like (2, 11, 7). I suggest comparing with range of +-15. This applies to all colors, not just black – N7D Apr 15 '20 at 14:57