0
votes

I'm trying to place an HTML div element over a three.js object. Most stackoverflow solutions offer a pattern similar to this:

// var camera = ...

function toScreenXY(pos, canvas) {
  var width = canvas.width, height = canvas.height;

  var p = new THREE.Vector3(pos.x, pos.y, pos.z);
  var vector = p.project(camera);

  vector.x = (vector.x + 1) / 2 * width;
  vector.y = -(vector.y - 1) / 2 * height;

  return vector;
}

I've tried many variations on this idea, and all of them agree on giving me this result:

console.log(routeStart.position); // target mesh
console.log(toScreenXY(routeStart.position));

// output:
// 
// mesh pos: T…E.Vector3 {x: -200, y: 200, z: -100}
// screen pos: T…E.Vector3 {x: -985.2267639636993, y: -1444.7267503738403, z: 0.9801980328559876}

The actual screen coordinates for this camera position and this mesh position are somewhere around x: 470, y: 80 - I determined them by hardcoding my div position. -985, -1444 are not even close to the actual screen coords :)

Please don't offer links to existing solutions if they follow the same logic as the snippet I provided. I would be especially thankful if someone could explain why I get these negative values, even though this approach seems to work for everyone else.

Here's a couple of examples using the same principle: Three.js: converting 3d position to 2d screen position Converting World coordinates to Screen coordinates in Three.js using Projection

1
When you make a statement regarding other solutions not working for you, you should link to those solutions to save time for those reading your question.Rotem
Those who are familiar with the topic will recognize the principle I described immediately. This seems to be a go-to solution for this problem. I would really appreciate the absence of non-essential comments. However, I have put in a couple of links to examples, you can check them out.Chris K

1 Answers

0
votes

Now, I've figured out the problem myself! Turns out, you can't project things before calling renderer.render(). It's very confusing that it gives you back weird negative coords. Hope other people will find this answer useful.