Search code examples
htmlcanvasclickpositiongeometric-arc

HTML5: Get click position from canvas arc


See this jsFiddle post for a working arc drawing; thanks to Simon Sarris for the fix in my previous questions.

I'm using the KineticJS plugin to create shapes and make use of event handlers. Assuming you clicked somewhere on the arc and the arc knew where you clicked (x, y), how could those 2 coordinates be used to determine a percentage?

When you click anywhere, the total percentage is always 100%.

Addin

To make this simpler, what could I do to (x, y) to virtually bend the object so that x goes from 0 to maximum x?


Solution

  • Simple trigonometry. sin(angle) = opposite / adjacent. opposite is the y value and adjacent is the x value. So Math.asin((xx - x) / (yy - y)) where xx and yy are the coords of the centre of the arc. That gives you the angle, which you can then divide 2 * Math.PI by.

    Off the top of my head I can't remember what happens with negative numbers. You may have to take the Math.abs value of the arguments, then work out which quadrant the click is in (easy to do by using < and >) and add Math.PI / 2 for each one.