我喜欢使用trig这样做,因为我觉得它很容易记住和使用。您只需要能够找到圆的顶部坐标和中心坐标并知道它的半径。而且你必须能够确定点击这两者的距离。因此可能必须使用偏移量。您可以修改此代码以满足您的特定需求。
如果您有点击的坐标,圆的中心和圆的顶部,您可以找到所有三个点之间的距离。拥有三角形每边的长度足以找到所有角度。
你唯一担心的角度是中心的角度。你可以使用那一个,相比之下你点击是否通过了中间的那个,找到圆圈的百分比。
以下是一些消息来源:
$('#circle').click(function (e) { //Relative ( to its parent) mouse position
var posX = $(this).position().left,
posY = $(this).position().top,
radius = 50,
x = e.pageX - posX, /* Offset not sure if cross-browser compatibile? */
y = e.pageY - posY,
coords = {
x:x,
y:y
};
function findDist( start, end ){
var dx = end.x;
var dy = end.y;
dx -= start.x;
dx *= dx;
dy -= start.y;
dy *= dy;
return Math.sqrt( dx + dy );
}
sideA = findDist(coords,{x:radius,y:0}); /* Click to Top Circle */
sideB = findDist(coords,{x:radius,y:radius}); /* Click to Center */
sideC = radius; /* Center to Middle */
function findAngleUsingSides(a, b, c) {
var radians = ((a * a) + (b * b) - (c * c)) / (2 * (a * b));
return (Math.acos(radians))/ Math.PI * 180;
}
A = findAngleUsingSides(sideB, sideC, sideA);
if(x < radius){
/*
You clicked before halfway across
*/
A = 360 - A;
}
percentClicked = A / 360;
console.log(percentClicked);
});