我制作了一个光线转换器来与 Canvas 内的某个对象相交。如果 Canvas 在窗口浏览器中单独存在,则效果很好,但如果我将 Canvas 放在其他某个 GUI 中,则它不会相交,因此 Canvas 的位置不同。我认为这是鼠标坐标的问题。我该如何调试它?如果我知道鼠标坐标,我怎么知道 Canvas 的坐标是什么?
function getPosition(event) {
// TODO: add the border of the canvas
var x = new Number();
var y = new Number();
if (event.x != undefined && event.y != undefined) {
x = event.x;
y = event.y;
} else {
// Firefox method to get the position
x = event.clientX + document.body.scrollLeft +
document.documentElement.scrollLeft;
y = event.clientY + document.body.scrollTop +
document.documentElement.scrollTop;
}
x -= canvas.offsetLeft;
y -= canvas.offsetTop;
return {x: x, y: y};
}
最佳答案
你需要的是:
// getBoundingClientRect() returns the element's position relative to the browser's visible viewport.
// clientX/Y returns the mouse position relative to the browser's visible viewport.
// we then just have to find the difference between the two to get the mouse position in "canvas-space"
var canvasPosition = renderer.domElement.getBoundingClientRect();
var mouseX = event.clientX - canvasPosition.left;
var mouseY = event.clientY - canvasPosition.top;
var mouseVector = new THREE.Vector2 (
2 * (mouseX / window.innerWidth) - 1,
1 - 2 * (mouseY / window.innerHeight));
然后你使用
mouseVector
为交叉点。
关于canvas - 调试threejs raycaster鼠标坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29809646/