three-chapter-img-2

今天绘制一个图形练练手

设置坐标位置 奇怪了! 坐标设置是(x, z, y)
cube.position.set(-10, 4, 0);

冰糖葫芦传、大花生

动画轨迹 —— 弹跳轨迹

1
2
3
step += 0.04;
sphere.position.x = 20 + (10 * (Math.cos(step)));
sphere.position.y = 2 + (10 * Math.abs(Math.sin(step)));

辅助动画库 ———— Stats.js 和 dat.gui.js

1 动态显示跟踪fps库 Stats.js

监测fps(画面每秒传输帧数),比如说 24fps,就是24帧每秒的意思。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

var stats = new Stats();
stats.showPanel(panelType); // 0: fps, 1: ms, 2: mb, 3+: custom
document.body.appendChild(stats.dom);

//调用时实时更新
function renderScene() {
// 实时更新
stats.update();

// rotate the cube around its axes
cube.rotation.x += 0.02;
cube.rotation.y += 0.02;
cube.rotation.z += 0.02;

// bounce the sphere up and down
step += 0.04;
sphere.position.x = 20 + (10 * (Math.cos(step)));
sphere.position.y = 2 + (10 * Math.abs(Math.sin(step)));

// render using requestAnimationFrame
requestAnimationFrame(renderScene);
renderer.render(scene, camera);
}

2 动态调节变量 dat.gui.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

// 创建一个对象,里面存放动态变量,并为其赋初始值
var controls = new function () {
this.rotationSpeed = 0.02; // 旋转速度
this.bouncingSpeed = 0.03; // 弹跳速度
};

var gui = new dat.GUI();
// 利用gui设置 动态值的 范围
gui.add(controls, 'rotationSpeed', 0, 0.5);
gui.add(controls, 'bouncingSpeed', 0, 0.5);

// 直接使用变量
cube.rotation.x += controls.rotationSpeed;

// bounce the sphere up and down
var step = 0;
step += controls.bouncingSpeed;
sphere.position.x = 20 + (10 * (Math.cos(step)));
sphere.position.y = 2 + (10 * Math.abs(Math.sin(step)));

窗口响应式调整

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

// 原来的设置相机
var camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000);

// 响应式
window.addEventListener('resize', onResize, false); //监听窗口变化

function onResize () {
// 设置透视摄像机的长宽比
camera.aspect = window.innerWidth / window.innerHeight
// 摄像机的 position 和 target 是自动更新的,而 fov、aspect、near、far 的修改则需要重新计算投影矩阵(projection matrix)
camera.updateProjectionMatrix()
// 设置渲染器输出的 canvas 的大小
renderer.setSize(window.innerWidth, window.innerHeight)
}

场景中的相关操作方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 移除
scene.remove(apple); // 该苹果烂了,被主人丢弃

// 遍历
scene.traverse(function(e)) { // 每一个子对象都会执行该函数,相当于遍历场景的中的子对象
e.rotation.x += 4;
})

// 场景中的所有对象,包括相机和光源
scene.children;
scene.children.length;

// 更加场景中的对象名 返回对象
scene.getObjectByName('cube-0');

场景遍历

1
 

场景雾化

1
2
3
4
5
6
7
// 指定颜色,近远
scene.fog = new THREE.Fog(color, near, far);
scene.fog = new THREE.Fog(0xffffff, 10, 100);

// 指定颜色,浓度
scene.fog = new THREE.FogExp2(color, 浓度);
scene.fog = new THREE.FogExp2(0xffffff, 0.015);

场景所有子对象统一材质

1
2
3
4
5

// 一旦设置后,场景中的所有对象都会中招,头上有绿,苍天饶过谁
scene.overrideMaterial = new THREE.MeshLambertMaterial({
color: 0x7cf265
});

灯光效果

光源