注意:下面的代码使用 WestLangley 的修复程序进行了更新。
我尝试了几个从 3D 投影到 2D 的示例。但是,当我尝试使用 projectVector 时,结果不在 -1 和 1 之间,因此当我乘以窗口的宽度/高度时,我得到的数字非常大(比我的屏幕分辨率大得多)。希望我的问题很简单。我使用的是three.min.js r56,我的内部窗口尺寸为1366x418。
下面的代码为 3D 点 (1200,625,100) 生成投影 (x,y):(-7.874704599380493,-13.403168320655823)。我知道我仍然需要将这个结果乘以窗口高度和宽度的一半,但是以像素为单位的结果 (x,y) 离屏幕很远。
<html>
<head>
<title>Test</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<script type="text/javascript" src="three.min.js"></script>
</head>
<body>
<canvas id='container'></canvas>
<script>
/// GLOBAL VARIABLES
var camera, scene, renderer, container, projector;
init();
function toXYCoord (object) {
var vector = projector.projectVector(object.position.clone(), camera);
return vector;
}
/// INIT
function init() {
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera( 50, window.innerWidth / window.innerHeight, 0.1, 20000 );
scene.add(camera);
camera.position.set(0,-1500,1500);
camera.lookAt(scene.position);
camera.updateMatrixWorld(); ///////////////// THIS IS THE FIX
projector = new THREE.Projector();
// sphere
var sphere = new THREE.Mesh( new THREE.SphereGeometry( 200, 32, 16 ), new THREE.MeshBasicMaterial({ color: 0x000000 }) );
sphere.position.set(1200,625,100);
scene.add(sphere);
container = document.getElementById('container');
renderer = new THREE.WebGLRenderer( { canvas: container, antialias:true } );
renderer.setSize( window.innerWidth, window.innerHeight );
var testVector = toXYCoord(sphere);
console.log(window.innerWidth + "x" + window.innerHeight);
console.log("Got: (" + testVector.x + "," + testVector.y + ")");
renderer.render( scene, camera );
}
</script>
</body>
</html>