Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get mouse position relative to pie chart (equation)

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:

Pie chart example

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.

like image 972
Simon Staton Avatar asked Jul 15 '14 10:07

Simon Staton


1 Answers

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;
}
like image 101
Alnitak Avatar answered Oct 18 '22 07:10

Alnitak