我正在学习如何使用Three JS制作3D动画,我正在尝试使用多个旋转立方体来制作3D动画。问题是整个画布在放大或缩小时或在移动设备上查看页面时不会调整大小,似乎相机会裁剪场景,因为对象保持相同的大小并且只显示部分动画。我想让整个画布的宽度等于浏览器窗口的宽度,以及任何屏幕宽度的比例尺寸的高度以及用户是否尝试放大或缩小。有人可以帮忙吗?提前谢谢。
<html>
<head>
<style>
body { margin: 0; }
canvas {
width: inherit !important;
height: inherit !important;
margin: 0 auto;
min-width: 300px;
min-height: 100px;
max-height: 485px;
max-width: 900px;
}
#anim{
margin: 0 auto;
max-width: 900px !important;
width: 100%;
background-color: grey;
}
</style>
</head>
<body>
<script src="js/three.min.js"></script>
<div id="anim">
</div>
<script>
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 8, window.innerWidth/window.innerHeight, 1, 1000 );
var div = document.getElementById("anim");
var renderer = new THREE.WebGLRenderer();
div.appendChild(renderer.domElement)
document.body.appendChild( div );
var cubes =[];
for ( i = 0; i <= 9; i++) {
var geometry = new THREE.BoxGeometry( 0.3, 0.3, 0.3 );
var material = new THREE.MeshBasicMaterial( { color: 0x00ff00, wireframe:true } );
var cube = new THREE.Mesh( geometry, material );
if(i<5){
cube.position.set(-1+(i/2),-0.4,0);
}else{
cube.position.set(-3.5+(i/2),0.4,0);
}
cubes[i] = cube;
scene.add(cubes[i]);
}
camera.position.z=10;
function render() {
for ( var i = 0 ; i < scene.children.length; i ++ ) {
var object = scene.children[ i ];
object.rotation.x += 0.01;
object.rotation.y += 0.1;
}
requestAnimationFrame( render );
renderer.render(scene, camera);
};
renderer.setSize( window.innerWidth, window.innerHeight);
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight);
}
window.addEventListener( 'resize', onWindowResize, false );
render();
</script>
</body>
</html>
答案 0 :(得分:0)
当我将此代码用于画布以响应所有窗口大小时,您可以在下面查看我的代码。
function render() {
if (resize(renderer)) {
camera.aspect = canvas.clientWidth / canvas.clientHeight;
camera.updateProjectionMatrix();
}
renderer.render(scene, camera);
requestAnimationFrame(render);
}
function resize(renderer) {
const canvas = renderer.domElement;
const width = canvas.clientWidth;
const height = canvas.clientHeight;
const needResize = canvas.width !== width || canvas.height !== height;
if (needResize) {
renderer.setSize(width, height, false);
}
return needResize;
}
window.addEventListener( 'resize', function() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight )
})