I want to add an onclick, onmouseover and an onmouseout events to individual shapes in a canvas element.
I have tried doing t
Added a more up-to-date answer: since this question was posted there are now two new techniques that can be used to detect local clicks in a canvas element:
Path2D: Paths can be stored on separate Path2D objects and checked using isPointInPath()addHitRegion: integrates with the event system which will allow you to check the event object itself of regions var path1 = new Path2D();
path1.rect(x1, y1, w, h); // add sub-path to Path2D object
var path2 = new Path2D();
path2.rect(x2, y2, w, h); // add sub-path to Path2D object
// now we can iterate through the objects to check which path we
// clicked without the need to rebuild each path as we did in the past
if (ctx.isPointInPath(path1, x, y)) { ... }
Read more about Path2D here. A polyfill exists as well.
// define a region using path
ctx.beginPath();
ctx.rect(x, y, w, h);
ctx.addHitRegion({id: "test"});
// now we can check in the event if the region was hit by doing:
canvas.addEventListener("mousemove", function(event){
if(event.region) {
// a region was hit, id can be used (see specs for options)
}
});
Read more about addHitRegion() here.
Note that it is still a bit early, both Firefox and Chrome supports this enabled via flags, other browsers will hopefully follow suit.