The easiest way to do this in HTML5 canvas is to take a snapshot of the image data for the canvas, and during mousemove look at the alpha color in the pixel under the mouse.
I will give a working example of this on my website here:
http://phrogz.net/tmp/canvas_detect_mouseover.html
Here is the kernel code I wrote. Pass it the context and the function and it will call your function with the RGBA components under the pixel.
function pixelOnMouseOver(ctx,callback){ var canvas = ctx.canvas; var w = canvas.width, h=canvas.height; var data = ctx.getImageData(0,0,w,h).data; canvas.addEventListener('mousemove',function(e){ var idx = (e.offsetY*w + e.offsetX)*4; var parts = Array.prototype.slice.call(data,idx,idx+4); callback.apply(ctx,parts); },false); }
And here is how it is used on this test page:
var wasOver; pixelOnMouseOver(ctx,function(r,g,b,a){ var isOver = a > 10; // arbitrary threshold if (isOver != wasOver){ can.style.backgroundColor = isOver ? '#ff6' : ''; wasOver = isOver; } out.innerHTML = "r:"+r+", g:"+g+", b:"+b+", a:"+a; });
source share