1、renderer.setSize会控制输出的canvas像素值这就像一个具有照片,改变页面上canvas尺寸,立方体被拉伸,这是canvas像素值和canvas的在页面尺寸不成比例,当这这两个宽高比不同时宽高的像素比例就不对,所以被拉伸。
<html>
<head>
<meta charset="utf-8">
<title>My first three.js app</title>
<style>
body {
margin: 0;
}
#c {
width: 100%;
height: 100%;
}
</style>
<canvas id="c"></canvas>
</head>
<body>
<script type="module">
import * as THREE from 'https://unpkg.com/three/build/three.module.js';
const canvas = document.querySelector('#c');
/*响应式正方体*/
const renderer = new THREE.WebGLRenderer({ antialias: true, canvas });
//场景
const scene = new THREE.Scene();
//相机
const fov = 75;
const aspect = 2; // 相机默认值
const near = 0.1;
const far = 5;
const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
camera.position.z = 2;
//物体
const boxWidth = 1;
const boxHeight = 1;
const boxDepth = 1;
const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth);
function makeInstance(geometry, color, x) {
const material = new THREE.MeshPhongMaterial({ color });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
cube.position.x = x;
return cube;
}
const cubes = [
makeInstance(geometry, 0x44aa88, 0),
makeInstance(geometry, 0x8844aa, -2),
makeInstance(geometry, 0xaa8844, 2),
]
renderer.render(scene, camera)
function resizeRendererToDisplaySize(renderer) {
//视图变化时,检测canvas的显示尺寸变化时宽高是否变化,发生变化重新通过renderer.setSize设置canvas像素值,当宽高比变化时相机宽高比变化
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
}
//光源
const color = 0xFFFFFF;
const intensity = 3;
const light = new THREE.DirectionalLight(color, intensity);
light.position.set(-1, 2, 4);
scene.add(light);
// //旋转立方体
function render(time) {
time *= 0.001;
if (resizeRendererToDisplaySize(renderer)) {
const canvas = renderer.domElement;
camera.aspect = canvas.clientWidth / canvas.clientHeight;
camera.updateProjectionMatrix();
}
cubes.forEach((cube, ndx) => {
const speed = 1 + ndx * .1;
const rot = time * speed;
cube.rotation.x = rot;
cube.rotation.y = rot;
});
renderer.render(scene, camera);
requestAnimationFrame(render);
}
requestAnimationFrame(render);
</script>
</body>
</html>
2、另一个问题是立方体看起来分辨率太低或者说块状化或者有点模糊。 将窗口拉伸的非常大你就能看到问题,这是因为窗口拉大几个像素点显示的信息相当于照片上原来的一个像素点信息,就模糊了