jumpa
jumpa

Reputation: 678

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 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);

I noticed that (0,0) in ThreeJS is actually in the center of the screen.

How do I convert any 2D coordinates from my canvas to 3D coordinates that work with ThreeJS. Any help is appreciated.

Upvotes: 0

Views: 3633

Answers (2)

It's Joker
It's Joker

Reputation: 65

First of all three js scene renders a 3Diamensonal which means to set position of your object should have all 3D co-ordinates ie.(X,Y,Z) in your scene if you want to change the position of your object use Object.position.set( x , y , z ); In which z position is used to put the objects position near far from camera enter image description hereenter image description here Good luck Put the z value 0 so you can put your object at the required co-ordinates (x,y,0)

Upvotes: 0

prisoner849
prisoner849

Reputation: 17596

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.

Upvotes: 1

Related Questions