将3d对象定位在画布的角上-three.js

时间:2018-07-17 13:52:11

标签: javascript canvas three.js

我有一个3d对象,无论画布的大小如何,我都希望它可以自动定位在画布的任一角。
default position of object in canvas

我遇到了这个stackoverflow解决方案:
change the initial position of my geometry

并将以下代码应用于我的对象:

mesh.position.set(-(window.innerWidth), (window.innerHeight), 0)

结果如下:

Object in the top left-hand corner of canvas

如您所见,它只是对象的一部分,我希望将其放置在全视图中,就像这样,但是在不同的画布尺寸(可能用于移动使用)上,它看起来必须保持一致:

object correctly positioned in corner

我还附上了我的设置示例

3d position

我只需要一些有关如何实现此目标的指示,因此,我们将不胜感激。

谢谢。

1 个答案:

答案 0 :(得分:0)

您可以将THREE.Raycaster()THREE.Plane()一起使用:

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 light = new THREE.DirectionalLight(0xffffff, 0.5);
light.position.set(0, 5, 10);
scene.add(light);
scene.add(new THREE.AmbientLight(0xffffff, 0.5));

var box = new THREE.Mesh(new THREE.BoxGeometry(2, 2, 2), new THREE.MeshLambertMaterial({
  color: "green"
}));
scene.add(box);

var plane = new THREE.Plane().setFromNormalAndCoplanarPoint(new THREE.Vector3(0, 0, 1), new THREE.Vector3(0, 0, 1));

btnMove.addEventListener("click", onClick, false);

var raycaster = new THREE.Raycaster();
var corner = new THREE.Vector2();
var cornerPoint = new THREE.Vector3();

function onClick() {
  corner.set(-1, -1); // NDC of the bottom-left corner
  raycaster.setFromCamera(corner, camera);
  raycaster.ray.intersectPlane(plane, cornerPoint);
  box.position.copy(cornerPoint)
    .add(new THREE.Vector3(1, 1, -1)); // align the position of the box
}

render();

function render() {
  requestAnimationFrame(render);
  renderer.render(scene, camera);
}
body {
  overflow: hidden;
  margin: 0;
}

#btnMove {
  position: absolute;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/94/three.min.js"></script>
<button id="btnMove">Move bottom-left</button>