I have created a canvas pie chart from an array of data, I am now trying to locate the mouse position relative to the pie chart to detect which section of data is being hovered. I am almost there but I am stuck on an equation.
My logic is functioning fine so I think this is more of a Maths question but will see what others think of my approach. here is my pie chart and the variables I am using:
The listed variables on the image are the variables that I have to use (mouseX, mouseY, distance from center, radius, circumfrence in pi and the section of data's point on the circumference relative to pi).
The starting section of the chart is from the right and starts at 0 of pi*2 to 100% of pi*2, the grey section then has a starting position of 1.34... relative to pie*2 and an end position of 2.228...
My main issue currently is using a pixel measurement to calculate it's position relative to pi. I could possibly check the position from top and left then work out the distance from center and work out the line from center depending on pi but I'm stumped on calculating this.
The hardest part to remember is that the Y coordinates run downwards in DOM coordinates, and therefore angles run clockwise from the positive X axis:
Given mouse position mx, my
:
var dx = mx - 180; // horizontal offset from center
var dy = my - 180; // vertical offset from center
var theta = Math.atan2(dy, dx); // angle clockwise from X-axis, range -π .. π
if (theta < 0) { // correct to range 0 .. 2π if desired
theta += 2.0 * Math.PI;
}
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