2015-04-22 82 views
2

我做了一个raycaster来交叉画布内的一些对象。如果画布在窗口浏览器中是独立的,但它不能获得交集,如果我将画布放在其他GUI中,并且画布的位置不同。我认为这是一个与鼠标坐标有关的问题。我该如何调试它?如果我知道鼠标坐标,我怎么能理解画布的坐标是什么?调试threejs raycaster鼠标坐标

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};  
} 

回答

4

你需要的是什么:

// 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的交集。

+0

如果这个或任何答案已解决您的问题,请考虑通过点击复选标记来接受它。这向更广泛的社区表明,您已经找到了解决方案,并为答复者和您自己提供了一些声誉。没有义务这样做。 – gaitat