canvas - 调试threejs raycaster鼠标坐标

标签 canvas three.js

我制作了一个光线转换器来与 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/

相关文章:

javascript - 将 Canvas 存储到本地存储并加载所有 Canvas 名称

javascript - 我的 Web 应用程序的 Canvas 绘图

javascript - 在 Blender 249.2 中将 NIF 转换为 OBJ 会产生不可见对象

javascript - 使用 ThreeJS 将 Vec3 数组传递给顶点着色器

javascript - ThreeJS 带按钮的相机控制

javascript - Three.js - 天空盒显示黑色

javascript - 如何通过kineticjs中的点之一拉线/多边形?

javascript - 使用 Firebase 存储上传 base64 图像

ios - 如何防止 sceneFunc() 每次都清除上下文?

javascript - 如何在加载 collada 纹理时调用函数? (三.js)