我正在尝试制作一个实用函数来确定从元素到鼠标光标的角度,但允许我们的开发人员更改 0 所在的位置。所以这需要通过 0deg 到 360degs 工作。
所以我正在尝试编写一个可以做到这一点的函数。我让它在正西工作为零,但需要让它在北、东和南工作为零。
出乎意料的困难。我曾尝试使用
90° × π/180 = 1.571rad
将弧度增加 90 度,但随后努力将其恢复到度数以进行返回。
function getAngleToCursor(el, evt, orientation = "north") {
const mouseX = evt.clientX
const mouseY = evt.clientY
const elRect = el.getBoundingClientRect()
const elX = elRect.left + elRect.width / 2
const elY = elRect.top + elRect.height / 2
const rads = Math.atan2(mouseY-elY, mouseX-elX)
let angle = 0
// Change where zero is located
switch(orientation) {
case "west":
angle = rads * 180 / Math.PI + 180
break;
case "north":
angle = ?
break;
case "east":
angle = ?
break;
case "south":
angle = ?
break;
}
return angle
}
好吧,我想我明白你的意思了。我在下面发布了更新:
function getAngleToCursor(el, evt, orientation = "north") {
// get normal angle from mouse to element
const mouseX = evt.clientX
const mouseY = evt.clientY
const elRect = el.getBoundingClientRect()
const elX = elRect.left + elRect.width / 2
const elY = elRect.top + elRect.height / 2
const rads = Math.atan2(mouseY-elY, mouseX-elX)
let angle = rads
const whole = Math.PI * 2
// Change where zero is located
switch(orientation) {
case "west":
angle -= whole / 4
break
case "north":
angle += 0
break
case "east":
angle += whole / 4
break
case "south":
angle += whole / 2
break
}
// convert angle to range between 0 and 360 (although we’re working in radians, of course)
angle = ((angle % whole) + whole) % whole
return angle
}
顺便说一句,我还没有测试过,但是这个概念很合理,尽管代码可能并不完美。