문제

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