I reread a bunch of examples, "how to find out the color of a pixel on the canvas." But whether I'm a fool (which is likely), or ...

In the code, I first fill the entire canvas with blue, then draw a picture on it. Clicking on canvas displays a message with a pixel color. But whatever picture I flooded, the conclusion is 0,0,255. If you do not fill with color, then 0,0,0.

<script type="text/javascript"> function Draw(){ var canvas=document.getElementById("can"); var ctx=canvas.getContext("2d"); ctx.fillStyle='#00f'; ctx.fillRect(0,0,200,200); var image=new Image(); image.src="./img.bmp"; image.onload=function(){ ctx.drawImage(image,0,0); } var img_data=ctx.getImageData(0,0,200,200); canvas.onclick=function(e){ var x=e.offsetX; var y=e.offsetY; var pix=img_data.data; var i=((y*200)+x)*4; var R=pix[i]; var G=pix[i+1]; var B=pix[i+2]; var rgb=R+','+G+','+B; alert(rgb); } } </script> 
  • @Anatoly Sivenko, If you are given an exhaustive answer, mark it as correct (click on the check mark next to the selected answer). - Nicolas Chabanovsky

2 answers 2

1) You get an img_data object before the picture is loaded. Accordingly, in this object only the blue fill data. To fix, for example, like this:

 // ... image.onload=function(){ ctx.drawImage(image,0,0); img_data=ctx.getImageData(0,0,200,200); // после загрузки картинки обновляем данные } var img_data=ctx.getImageData(0,0,200,200); 

2) do not forget that you cannot access files obtained from another server using getImageData.

If you are not working on a web server, but the path "./img.bmp" implies "file://C:\img.bmp" , then the browser will write an error to the console:

Unable to get data from the canvas because the canvas has been tainted by cross-origin data.

To fix, you need to start a local web server to access resources via http://localhost/...

    1) offsetX and offsetY works only in Chrome. For compatibility with at least FF:

     if(e.offsetX==undefined) { // Firefox var x = e.pageX-$(canvas).offset().left; var y = Math.round(e.pageY-$(canvas).offset().top); } else { // Google Chrome var x = e.offsetX; var y = e.offsetY; } 

    2) You hang up the click processing and fill in the pix before the image is loaded, so this array is all blue.

    To access the image, you need to slightly change the image.onload:

      var image=new Image(); var pix; image.onload=function(){ ctx.drawImage(image,0,0, 128,128); var img_data=ctx.getImageData(0,0,128,128); pix = img_data.data; } image.src="./share/images/kchart.png"; 

    and in canvas.onclick line var pix = img_data.data remove altogether.

    http://test.controlcash.ru/canvas.html