Is it possible to get the RGB value pixel under the mouse? Is there a complete example of this? Here’s what I have so far:
function draw() {
var ctx = document.getElementById('canvas').getContext('2d');
var img = new Image();
img.src = 'Your URL';
img.onload = function(){
ctx.drawImage(img,0,0);
};
canvas.onmousemove = function(e) {
var mouseX, mouseY;
if(e.offsetX) {
mouseX = e.offsetX;
mouseY = e.offsetY;
}
else if(e.layerX) {
mouseX = e.layerX;
mouseY = e.layerY;
}
var c = ctx.getImageData(mouseX, mouseY, 1, 1).data;
$('#ttip').css({'left':mouseX+20, 'top':mouseY+20}).html(c[0]+'-'+c[1]+'-'+c[2]);
};
}
Here’s a complete, self-contained example. First, use the following HTML:
Then put some squares on the canvas with random background colors:
And print each color on mouseover:
The code above assumes the presence of jQuery and the following utility functions:
See it in action here: