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

有帮助吗?

解决方案

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!

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top