渲染两步骤:
- 初始化;
- 定义用户接口;
- 开启渲染循环;
- 调用用户接口。
渲染循环七要素:
- 定义渲染器和渲染窗口;
- 定义场景;
- 定义摄像机;
- 定义光照;
- 定义几何体;
- 定义材质贴图;
- 将所有物体添加到场景中。
下面是上述过程的具体代码(注意其中的框架结构):
import * as THREE from './threejs_lib/build/three.module.js';
var camera, cube, scene, renderer;
var defaultMaterial;
init();
renderLoop();
function init() {
// renderer definition
renderer = new THREE.WebGLRenderer({
canvas: document.getElementById('mainCanvas')
});
renderer.setClearColor(0x000000); // black
// scene definition
scene = new THREE.Scene();
// camera definition
//camera = new THREE.OrthographicCamera(-2, 2, 1.5, -1.5, 1, 10); // or THREE.PerspectiveCamera(45, 4 / 3, 1, 1000);
camera = new THREE.PerspectiveCamera(-2, 2, 1.5, -1.5, 1, 10); // or THREE.PerspectiveCamera(45, 4 / 3, 1, 1000);
camera.position.set(0, 0, 5);
scene.add(camera);
// 2. material definition
defaultMaterial = new THREE.MeshBasicMaterial({ color: 0xff0055, flatShading: true, vertexColors: THREE.VertexColors });
// 1. geometry definition
cube = new THREE.Mesh(new THREE.CubeGeometry(1, 2, 3),
defaultMaterial
);
cube.position.x = 0;
cube.position.y = 0;
cube.position.z = 0;
cube.rotation.x = 0;
cube.rotation.y = 0;
cube.rotation.z = 0;
scene.add(cube);
}
function operation() {
cube.rotation.y += 0.1;
console.log(cube.position.x);
if (cube.position.x < 0) {
cube.position.x += 0.01;
} else if (cube.position.x >= 0) {
cube.position.x -= 0.5;
}
if (cube.position.x >= 2) {
cube.position.x -= 0.01;
}
}
function renderLoop() {
// operate via user interaction
operation();
// render
renderer.render(scene, camera);
requestAnimationFrame(renderLoop);
}
[将上方代码添加到HTML文件中即可查看效果]
作者:艾孜尔江