Question

I am using canvas with gradient (fill-colour varying from actual value to whitish) to pick the colour at any point (on mouse click) using canvas function getimagedata

Wired problem : Canvas.getImageImadata gives wrong values somewhere and correct one mostly

JSFIDDLE Demo

Était-ce utile?

La solution

You need to correct the mouse position so it becomes relative to canvas. By default it is relative to client window.

To correct you can do the following:

$('#myCanvas').click(function(e) {

    var r = $('#myCanvas')[0].getBoundingClientRect();  // get canvas abs. pos.
    //OR
    //var r = $('#myCanvas').position();
    x = e.clientX - r.left;                             // make relative
    y = e.clientY - r.top;

    var data=ctx.getImageData(x,y,1,1).data;

    $('#feedback').html("Red : "+data[0]+" __  Green : " +
                        data[1]+" __  Blue : "+data[2]+" __  Alpha : "+data[3])
});

Otherwise you would sample outside the canvas which would give a blank ImageData object.

Modified fiddle

Hope this helps!

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top