Reputation: 697
Alright, I have a HTML canvas with a bunch of circles on it. I want mouseclick events on circles to trigger some Javascript function. I already have the basics, but the coordinates are obviously so precise that it takes me like 30 times to hit the exact coordinates of a certain circle.
Is there a way I could implement an "about equal to"; in other words, I would like the x and y of the mouseclick to trigger a function when it's pretty close to (let's say 10px) the coordinates of something on canvas?
Thanks
Alex
Upvotes: 1
Views: 462
Reputation: 736
General case, you want to check if you have clicked within a polygon created by expanding your curve outward in both left and right directions. Calculation of this polygon in the case of bezier curves, general conic sections, etc. is tricky. Most graphic libraries allow you to set a stroke-width parameter and do it for you. Draw a wide curve in background color below your 1px curve and check for hits on the wide one. Just make sure you draw all the background color ones before any of the foreground color ones.
In your specific case of circles, if you don't have such a graphic library, it will suffice to see if you have clicked within your tolerance of a distance from the circle center. If you have a very small number of circles you can go through the whole list. If you have more than a half dozen (gut feel for when to cut over to better algorithm) divide the screen up into quarters with a list of which circles a hit in one of the rectangles might have hit, then divide into quarters within that rectangle and check with circles it might be until you have just a half dozen or so possibilities. Then go down the list of possibilities checking if you are within your delta for any of the circles.
Upvotes: 0
Reputation: 10119
You can use something like this to test if one point is within a certain radius of another point:
function withinRadius (x1, y1, x2, y2, radius) {
var dX = x1 - x2, dY = y1 - y2;
return ((dX*dX) + (dY*dY) < radius*radius);
}
Upvotes: 3
Reputation: 728
First thoughts:
if ((mouselocx >= (corodinatex - 10)) && (mouselocx <= (corodinatex + 10)) {
if ((mouselocy >= (corodinatey - 10)) && (mouselocy <= (corodinatey + 10)) {
Do something...
}
}
Upvotes: 1