ThreeJS - 2D 像素到 3D 坐标转换 [英] ThreeJS - 2D pixels to 3D coordinates conversion

查看:71
本文介绍了ThreeJS - 2D 像素到 3D 坐标转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将在 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>

此外,您可以使用光线投射器和 THREE.Plane() 做类似的事情,找到光线投射器的光线与平面的交点.

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屋!

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