我有一个非常简单的测试场景,可以在场景中的3d对象的位置放置一堆html标签。但是,当我尝试将3d坐标转换为屏幕位置时,我会得到奇怪的值,这些值根本不会与我的3d对象的位置发生冲突。请参阅下面的代码,我将使用该代码生成场景并放置标签:
var CanvasContainer = document.getElementById("KettingContainer");
function CameraSetup(container){
var camera = new THREE.PerspectiveCamera( 50, container.offsetWidth / container.offsetHeight, 1, 300 );
camera.position.set( 0, 0, 100 );
camera.lookAt( 0, 0, 0 );
return camera;
}
function SceneSetup(){
var scene = new THREE.Scene();
return scene;
}
function RenderSetup(container) {
var renderer = new THREE.WebGLRenderer({ alpha: true });
renderer.autoClear = false;
renderer.setClearColor( 0x000000, 0 );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( container.offsetWidth, container.offsetHeight );
container.appendChild( renderer.domElement );
return renderer;
}
function OnWindowResize(container){
camera.aspect = container.offsetWidth / container.offsetHeight;
camera.updateProjectionMatrix();
renderer.setSize( container.offsetWidth, container.offsetHeight );
}
var kraalLabels = document.getElementById('kraalLinkLabels').getElementsByTagName('div');
function Animate(){
requestAnimationFrame(Animate);
Render();
}
function Render(){
renderer.render( scene, camera );
}
function createScreenVector(pos, camera, width, height) {
const hw = width/2, hh = height/2;
var pos2d = pos.clone();
pos2d.project(camera);
console.log(pos2d);
pos2d.x = ( pos2d.x * hw ) + hw;
pos2d.y = - ( pos2d.y * hh ) + hh;
return pos2d;
}
function positionLabels(positions, camera, width, height){
for( var i = 0; i < kraalLabels.length; i++ )
{
const d = createScreenVector(positions, camera, width, height);
kraalLabels[i].style.left = d.x + "px";
kraalLabels[i].style.top = d.y + "px";
}
}
var camera = CameraSetup(CanvasContainer);
var scene = SceneSetup();
var renderer = RenderSetup(CanvasContainer);
console.log("fc: ", camera.position);
const geometry = new THREE.SphereGeometry( 10, 32, 32 );
const material = new THREE.MeshBasicMaterial( {color: 0xff0000} );
let sphere = new THREE.Mesh( geometry, material );
sphere.position.set(20, 20, 0.1);
scene.add( sphere );
positionLabels(new THREE.Vector3(20, 20, 0.1), camera, CanvasContainer.offsetWidth, CanvasContainer.offsetHeight);
window.addEventListener("resize", function(){ OnWindowResize(CanvasContainer); }, false);
Animate();
请参阅下面的相机位置,画布容器大小和每个标签的屏幕位置的屏幕截图:
正如您所看到的,标签的位置比画布本身大得多。这些职位都是负面的......
即使我的对象只是在屏幕中心的顶部和左侧。
我完全被困在这个时候我不知道我做错了什么:(
如果需要额外的信息,我很乐意澄清!
在几个小时后搜索一个解决方案后,我终于在你做vector3.project(camera);
之前找到了问题,你必须像这样更新相机矩阵:camera.updateMatrixWorld();
这将解决奇怪值的问题。
希望这有助于未来的人!