gpt4 book ai didi

javascript - 将3d对象定位在 Canvas 的 Angular 上-three.js

转载 作者:行者123 更新时间:2023-12-04 00:59:12 28 4
gpt4 key购买 nike

我有一个3d对象,无论 Canvas 的大小如何,我都希望它可以自动定位在 Canvas 的任一角。
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

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

object correctly positioned in corner

我还附上了我的设置示例

3d position

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

谢谢。

最佳答案

您可以将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>

关于javascript - 将3d对象定位在 Canvas 的 Angular 上-three.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51383187/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com