ThreeJS-2D像素到3D坐标转换 [英] ThreeJS - 2D pixels to 3D coordinates conversion
问题描述
我试图将在ThreeJS中创建的 cube
渲染到特定位置的HTML canvas
上.
I am trying to render a cube
created in ThreeJS onto a HTML canvas
at a particular position.
我的位置以像素为单位.像(100,200).我不知道如何将这些像素转换为ThreeJS坐标.
I have the position in pixels. Like (100,200). I cannot figure out how to convert these pixels to ThreeJS coordinates.
// My canvas is 640 X 480
var CANVAS_WIDTH = 640;
var CANVAS_HEIGHT = 480;
// Create and cube to scene
var geometry = new THREE.CubeGeometry(1, 1, 1);
var materials = createMaterials();
this.cube = new THREE.Mesh( geometry, materials );
this.cube.doubleSided = true;
this.scene.add(this.cube);
// Create and add camera
this.camera = new THREE.PerspectiveCamera(45, CANVAS_WIDTH / CANVAS_HEIGHT, 1, 5000);
this.camera.position.z = CANVAS_WIDTH / 2;
this.scene.add(this.camera);
我注意到ThreeJS中的(0,0)实际上在屏幕中央.
I noticed that (0,0) in ThreeJS is actually in the center of the screen.
如何将画布上的任何2D坐标转换为与ThreeJS一起使用的3D坐标.感谢您的帮助.
How do I convert any 2D coordinates from my canvas to 3D coordinates that work with ThreeJS. Any help is appreciated.
推荐答案
使用 THREE.Raycaster()
:
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.set(0, 0, 10);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
var box = new THREE.Mesh(new THREE.BoxBufferGeometry(), new THREE.MeshBasicMaterial({
color: "red",
wireframe: true
}));
scene.add(box);
var raycaster = new THREE.Raycaster();
var mouse = new THREE.Vector2();
document.addEventListener("mousedown", onMouseDown);
function onMouseDown(event) {
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
raycaster.setFromCamera(mouse, camera);
var dist = box.position.clone().sub(camera.position).length();
raycaster.ray.at(dist, box.position);
}
renderer.setAnimationLoop(() => {
renderer.render(scene, camera);
});
body {
overflow: hidden;
margin: 0;
}
<script src="https://threejs.org/build/three.min.js"></script>
此外,您可以使用raycaster和 THREE.Plane()
做类似的事情,找到raycaster射线与平面的交点.
Also, you can do something similar, using a raycaster and THREE.Plane()
, finding the intersection point of raycaster's ray with the plane.
这篇关于ThreeJS-2D像素到3D坐标转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!