Reputation: 1004
I need to select a particular color in canvas and get an RGB value for that color. Can anyone please help me to do this?
Here is the code for canvas
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var grd=ctx.createLinearGradient(0,0,200,0);
grd.addColorStop(0,"red");
grd.addColorStop(0.15,"yellow");
grd.addColorStop(0.3,"green");
grd.addColorStop(0.45,"aqua");
grd.addColorStop(0.6,"blue");
grd.addColorStop(0.7,"fuchsia");
grd.addColorStop(1,"red");
Upvotes: 3
Views: 116
Reputation: 2442
With jQuery:
// utility function to retrieve click position inside the canvas
function findPos(obj) {
var curleft = 0, curtop = 0;
if (obj.offsetParent) {
do {
curleft += obj.offsetLeft;
curtop += obj.offsetTop;
} while (obj = obj.offsetParent);
return { x: curleft, y: curtop };
}
return undefined;
}
$('#myCanvas').click(function(e) {
var pos = findPos(this);
var x = e.pageX - pos.x;
var y = e.pageY - pos.y;
var coord = "x=" + x + ", y=" + y;
var c = this.getContext('2d');
var p = c.getImageData(x, y, 1, 1).data; // get 1x1 pixels area at the (x,y) position
var red_value = p[0];
var green_value = p[1];
var blue_value = p[2];
});
Upvotes: 1