简体   繁体   中英

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.
对象在画布中的默认位置

I came across this stackoverflow solution:
更改几何的初始位置

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

3D位置

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() :

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM