如果画布不是全屏,ThreeJS Raycaster 不会找到相交的对象 [英] ThreeJS Raycaster doesn't find intersected objects if canvas isn't full screen

查看:47
本文介绍了如果画布不是全屏,ThreeJS Raycaster 不会找到相交的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 ThreeJS 在画布元素中创建了一个包含多个对象的场景.如果用户点击它,我现在想改变它的材质颜色.

I created a scene with multiple objects in the canvas element with ThreeJS. I now want to change the material color of an object if the user clicks on it.

我的 Angular 5 组件的摘录,其中包含所有 ThreeJS 内容:

Excerpt of my Angular 5 component, which holds all the ThreeJS content:

public onMouseDown(event: MouseEvent) {
    console.log("onMouseDown");
    event.preventDefault();

    var rayCaster = new THREE.Raycaster();
    var mouse = new THREE.Vector2();

    mouse.x = (event.clientX / this.renderer.domElement.clientWidth) * 2 - 1;
    mouse.y = -(event.clientY / this.renderer.domElement.clientHeight) * 2 + 1;

    rayCaster.setFromCamera(mouse, this.camera);

    var intersects = rayCaster.intersectObjects(this.scene.children);

    console.log("Scene has " + obj.length + " objects");
    console.log(intersects.length + " intersected objects found");

    intersects.forEach((i) => {
      i.object.material =
        new THREE.MeshBasicMaterial({color: 0xf1f11f});
    });
    this.render();
}

问题是鼠标坐标不正确,由于canvas元素和文档外边缘之间的距离.每当我在场景中单击时,鼠标右侧的对象将获得新的材质颜色.

The problem is that the mouse coordinates are not correct, due to the distance between canvas element and the document outer edge. Whenever I click in the scene, an object right of the mouse will get the new material color.

一些信息:this.renderer.domElement.clientWidth 保存画布元素的宽度

Some information: this.renderer.domElement.clientWidth holds the width of the canvas element

如果画布元素不是全屏,如何计算正确的鼠标坐标?

How to calculate the correct mouse coordinates if the canvas element isn't full screen?

推荐答案

如果您的流程中断(您的容器浮动或手动定位),则 clientX/clientY将报告坏"值(相对于页面,而不是您可能期望的容器).属性 offsetX/offsetY 帐户为此,报告与触发事件的容器相关的值.

If your flow is broken (your container is floated or manually positioned), then clientX/clientY will report "bad" values (relative to the page, rather than to the container like you might expect). The properties offsetX/offsetY account for this by reporting values relative to the container on which the event was fired.

根据 MDN,支持有限,但我刚刚的测试(01/22/2018)显示最新版本的 Chrome、Firefox、Edge 和 IE 都报告了正确的值*.请注意,某些浏览器会报告整数值,而其他浏览器可能会报告双精度值.

According to MDN, support is limited, but my testing just now (01/22/2018) showed the latest versions of Chrome, Firefox, Edge, and IE all reported the correct values*. Just note that some browsers report integer values, while others may report double values.

*这可能不适用于 Safari 或移动浏览器.天啊.

这篇关于如果画布不是全屏,ThreeJS Raycaster 不会找到相交的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆