屏幕坐标的3d位置无法正常运行三个js [r100]

时间:2019-03-05 11:50:19

标签: javascript canvas three.js 3d 2d

我有一个非常简单的测试场景,可以将一堆html标签放在场景中3d对象的位置上。但是,当我尝试将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();

请参见下面的屏幕快照,其中包括每个标签的摄像头位置,画布容器大小和屏幕位置:

fc is the position of the camera

如您所见,标签的位置比画布本身大得多。位置全都是负数...

我的对象甚至位于屏幕中心的顶部和左侧。

这一次我完全被困住了,我不知道我在做什么错:(

如果需要更多信息,我很乐意澄清!

1 个答案:

答案 0 :(得分:1)

经过数小时的努力寻找解决方案之后,我终于在执行vector3.project(camera);之前就发现了问题,您必须像这样更新相机矩阵:camera.updateMatrixWorld();将解决具有奇怪值的问题。

希望这对以后的人有帮助!