在网上找了好久,终于功夫不负有心人。终于被我找到了。哈哈!
附上原文链接:
https://stackoverflow.com/questions/13055214/mouse-canvas-x-y-to-three-js-world-x-y-z
实现代码:
/**
*
* @param {Number} x 屏幕坐标 x
* @param {Number} y 屏幕坐标 y
* @param {Document} domContainer 存放元素的容积
* @param {THREE.PerspectiveCamera} camera 相机
* @param {Number} targetZ z轴 默认为0
*/
screenPointToThreeCoords(x, y, domContainer, camera, targetZ) {
var vec = new THREE.Vector3(); // create once and reuse
var pos = new THREE.Vector3(); // create once and reuse
vec.set(
( x / domContainer.clientWidth ) * 2 - 1,
- ( y / domContainer.clientHeight ) * 2 + 1,
0.5 );
vec.unproject( camera );
vec.sub( camera.position ).normalize();
var distance = (targetZ - camera.position.z) / vec.z;
pos.copy( camera.position ).add( vec.multiplyScalar( distance ) );
return pos;
},
代码解释,网上复制过来的
原文链接
https://discourse.threejs.org/t/project-a-2d-screen-point-to-3d-world-point/5713
As I understand,
after the line:
vec.set( ( event.clientX / window.innerWidth ) * 2 - 1, - ( event.clientY / window.innerHeight ) * 2 + 1, 0.5 );
vec is the position of a 3D point (pointA) in space along the ray in Normalized Device Coordinates
after the line:
vec.unproject( camera );
vec is the position of pointA in 3D space in world coordinates
after the line:
vec.sub( camera.position ).normalize();
vec is the normalized ray direction from the camera
after the line:
var distance = ( targetZ - camera.position.z ) / vec.z;
distance is the distance/scale by which to travel along the ray, until reaching a point on the ray which lies in plane z=targetZ
after the line:
pos.copy( camera.position ).add( vec.multiplyScalar( distance ) );
pos is the position of the 3D point (pointB) which lies on the ray and is at z==targetZ
最后附上我设置的
this.subRenderer = new THREE.CSS3DRenderer();
this.subCamera = new THREE.PerspectiveCamera(45, this.$subContainer.clientWidth / this.$subContainer.clientHeight, 1, 10000);
this.subScene = new THREE.Scene();
this.subControls = new THREE.TrackballControls(
this.subCamera,
this.subRenderer.domElement,
);
// 重新绘制
subRender() {
this.subRenderer.render(this.subScene, this.subCamera);
},
祝兄弟早日找到自己想要的答案