I have a canvas with some irregular shape drawings in it, and I would like to have a feedback when someone clicks on a specific one?
I've been looking everywhere for this and have only found solutions for rectangle.
I think it may have to do with isPointInPath(), but I've yet to find a concise explanation on how to use it.
Any help welcome.
I made a tutorial that uses a second invisible canvas to do object picking/hit testing. Draw all your shapes, one by one, onto the second canvas until one of them has a black pixel where the mouse location is. Then you've found your object!
Here's a bit from the tutorial I wrote on selecting objects with canvas:
// gctx is ghost context, made from the second canvas
// clear(gctx)
// ...
// run through all the boxes
var l = boxes.length;
for (var i = l-1; i >= 0; i--) {
// draw shape onto ghost context
drawshape(gctx, boxes[i], 'black', 'black');
// get image data at the mouse x,y pixel
var imageData = gctx.getImageData(mx, my, 1, 1);
var index = (mx + my * imageData.width) * 4;
// if the mouse pixel exists, select and break
if (imageData.data[3] > 0) {
mySel = boxes[i];
offsetx = mx - mySel.x;
offsety = my - mySel.y;
mySel.x = mx - offsetx;
mySel.y = my - offsety;
isDrag = true;
canvas.onmousemove = myMove;
invalidate();
clear(gctx);
return;
}
}
My full demo only uses rectangles but in a later version I will use circles/paths/text.
If you want to see the demo and my full code it is here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With