ThreeJS - 2D Pixels To 3D Coordinates Conversion
I am trying to render a cube created in ThreeJS onto a HTML canvas at a particular position. I have the position in pixels. Like (100,200). I cannot figure out how to convert these
Solution 1:
Just an option of how you can do it, using 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>
Also, you can do something similar, using a raycaster and THREE.Plane()
, finding the intersection point of raycaster's ray with the plane.
Post a Comment for "ThreeJS - 2D Pixels To 3D Coordinates Conversion"