Get mouse position relative to pie chart (equation)

让人想犯罪 __ 提交于 2020-01-03 09:12:06

问题


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.


回答1:


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;
}


来源:https://stackoverflow.com/questions/24755292/get-mouse-position-relative-to-pie-chart-equation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!