Find out the color of the pixel of the image drawn in canvas

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

In the code, I first fill the entire canvas with blue, then draw a picture on it. When you click on the canvas, a message is displayed with the color of the pixel. But no matter what picture I filled, the output is 0,0,255. If you do not fill it 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>
Author: Виталина, 2015-03-01

2 answers

1) You get the img_data object before the image is loaded. Accordingly, this object contains only data about the blue fill. 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) don't forget that you can't access files received from another server using getImageData .

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

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

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

 2
Author: atwice, 2017-05-23 12:39:14

1) offsetX and offsetY only works 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 loads, 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, remove the line var pix = img_data.data altogether.

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

 2
Author: Борис, 2015-03-02 15:37:12