Threejs 学习记录:第一个三维立体场景
第一个三维立体场景
跟随官方示例创建一个带有旋转立方体的场景了解three.js基础知识。
创建场景三要素:场景、相机、渲染器
three.js 进行场景渲染需要三样东西:场景Scene、相机Camera和渲染器Renderer,即使用相机在渲染器上渲染场景。
既然是相机,就需要调整参数,官方示例中的PerspectiveCamera 接收四个参数:视野FOV(场景范围) 横纵比(相机渲染的宽高比例) 近剪切平面 远剪切平面 ,文档说明远近剪切屏幕,表示距离相机超出远近剪切平面值的对象不会被渲染。
渲染器即canvas中的画布,需要设置在应用程序中渲染的大小,并添加到HTML文档中。
// 场景
const scene = new THREE.Scene();
// 相机
const camera = new THREE.PerspectiveCamera(
75,
window.innerWidth / window.innerHeight,
0.1,
1000
);
// 渲染器
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth,window.innerHeight);
document.body.appendChild(renderer.domElement);
添加场景主体:旋转立方体
BoxGeometry: 立方体对象
MeshBasicMaterial:着色器
Mesh: 网格
const geometry = new THREE.BoxGeometry( 1, 1, 1 );
const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
const cube = new THREE.Mesh( geometry, material );
scene.add( cube );
camera.position.z = 5;
渲染场景
添加了以上内容后,应用程序仍无法渲染内容,实际渲染场景还需调用renderer方法:
render:渲染
requestAnimationFrame: 循环渲染 导致渲染器每次刷新屏幕时绘制场景 (一般默认保持60FPS的频率)
当用户导航到其他浏览器选项卡时 requestAnimationFrame 会暂停。
function animate() {
requestAnimationFrame( animate );
renderer.render( scene, camera );
}
animate();
动画立方体
添加上述代码后,只能看到一个绿色的正方体,现在为这个正方体添加动画,从而看到一个旋转的立方体。
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
在渲染函数中添加立方体的旋转动画:修改立方体的横纵轴值。
在应用程序运行时想要移动或更改的任何内容都必须经过动画循环,因此,在场景中的动画渲染操作都需要放在渲染函数 animate 中。
整体代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>three.js</title>
<style>
body {
margin: 0;
}
</style>
</head>
<body>
<script src="https://unpkg.com/three@0.142.0/build/three.js"></script>
<script>
const scene = new THREE.Scene();
// 相机 paramter
const camera = new THREE.PerspectiveCamera(
75,
window.innerWidth / window.innerHeight,
0.1,
1000
);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
const geometry = new THREE.BoxGeometry( 1, 1, 1 );
const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
const cube = new THREE.Mesh( geometry, material );
scene.add( cube );
camera.position.z = 5;
function animate() {
requestAnimationFrame( animate );
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render( scene, camera );
};
animate();
</script>
</body>
</html>