我做了一个raycaster来交叉画布中的一些对象。如果在窗口浏览器中单独使用canvas,但是如果我将canvas放在其他GUI中并且因此画布的位置不同,它就不会得到交集。我认为这是鼠标坐标的问题。我该怎么调试呢?如果我知道鼠标坐标怎样才能理解画布的坐标是什么?
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};
}
答案 0 :(得分:6)
你需要的是:
// 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
进行交集。