提问人:Yonk 提问时间:11/11/2023 更新时间:11/11/2023 访问量:29
如何在 vanilla JS 中将鼠标拖动转换为围绕 3D 对象的旋转?
How can you translate mouse drag to rotation about a 3D object in vanilla JS?
问:
我试图做的是将鼠标拖动 (x,y) 沿屏幕转为 3D 对象(在本例中为球体)的完全旋转 (在撰写本文时,我没有包含堆栈代码片段的选项,因此我将链接一个 jsfiddle 并在块中包含一些示例代码)
// Handle click
canvas.onmousedown = (e) => {
e.preventDefault()
let pos1 = e.pageX
let pos2 = e.pageY
if (e.button == 0) {
document.onmousemove = (e) => {
canvas.style.cursor = 'grabbing'
let pos3 = pos1 - e.pageX
let pos4 = pos2 - e.pageY
for (let i = 0; i < Spheres.length; i++) {
Spheres[i].move_centre(-pos3 / scale,-pos4 / scale)
}
pos1 = e.pageX
pos2 = e.pageY
}
} else if (e.button == 2) {
document.onmousemove = (e) => {
canvas.style.cursor = 'grabbing'
let pos3 = pos1 - e.pageX
let pos4 = pos2 - e.pageY
let delta = vector(pos3, pos4, 0)
let angle = sqrt(pos3**2 + pos4**2) * (PI / 180)
let rotaxis = vector.normalize(vector.cross(vector(0,0,-1), delta))
let axisangle = vector(rotaxis.x * angle, rotaxis.y * angle, rotaxis.z * angle)
for (let i = 0; i < Spheres.length; i++) {
let circumference = (2 * Spheres[i].Radius) * PI
let o = vector.mul(vector(Spheres[i].gamma, Spheres[i].phi, Spheres[i].theta), axisangle)
Spheres[i].gamma += o.x
Spheres[i].phi += o.y
Spheres[i].theta += o.z
//Spheres[i].gamma += -(pos3 / circumference) / scale * 2
//Spheres[i].phi += (pos4 / circumference) / scale * 2
//Spheres[i].theta += (deltaz/scale) / circumference / 100
}
pos1 = e.pageX
pos2 = e.pageY
}
}
document.onmouseup = (e) => {
document.onmousemove = null
canvas.style.cursor = 'auto'
}
}
我使用此页面来大致了解它是如何完成的,但在示例中,我无法重现与它描述的相同的结果。我不明白我是否错误地遵循了说明,是否错误地假设了某些事情或任何其他问题。
答: 暂无答案
评论