[英]Positioning a 3d object in the corners of the canvas - three.js
I have a 3d object that I want to be able to automatically position in either corner of my canvas regardless of the canvas's size. 我有一个3d对象,无论画布的大小如何,我都希望它可以自动定位在画布的任一角。
I came across this stackoverflow solution: 我遇到了这个stackoverflow解决方案:
and applied the following code to my object: 并将以下代码应用于我的对象:
mesh.position.set(-(window.innerWidth), (window.innerHeight), 0)
which results in this: 结果是:
As you can see it is only part of the object and I would like to have it positioned in full view, like this, but it would need to look consistent on different canvas sizes (maybe for mobile use): 如您所见,它只是对象的一部分,我希望将其放置在全视图中,就像这样,但是在不同的画布尺寸(可能用于移动使用)上,它看起来必须保持一致:
I have also attached an example of my setup 我还附上了我的设置示例
I just need some pointers on how I can achieve this, so any help would be most appreciated. 我只需要一些有关如何实现此目标的指示,因此,我们将不胜感激。
Thanks. 谢谢。
You can use THREE.Raycaster()
with THREE.Plane()
: 您可以将
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.