I made a raycaster to intersect some object inside canvas. It works good if canvas is alone in the window browser but it doesn't get intersection if I put canvas inside some other GUI and so the position of canvas is different. I think it is a problem with mouse coordinates. How can I debug it? If I know mouse coordinates how can I understand what is the coordinate of 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};
}
what you need to is:
// 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));
and you use mouseVector
for intersection.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With