es6 three.js 开发

移除场景 清空内存 性能优化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
移除场景有效,会在div中删除canvas。
document.getElementById(webglDivId).removeChild(renderer.domElement);
m.dispose(); 需要dispose 所有的网格和材质

//渲染动画
let globalID;
function render() {
globalID = requestAnimationFrame(render);
renderer.render(scene, camera);
}
//套路一下 也许有用
cancelAnimationFrame(globalID); //取消定时器,先得给定时器命名。
THREE.Cache.clear() // 清除cache
scene = null; //设置null ,需要先取消定时器
document.getElementById(webglDivId).removeChild(renderer.domElement); // 删除canvas
1
2
3
4
5
6
7
8
9
10
11
//这个移除是测试是有效的
function removePoint(name) {
let mesh = scene.getObjectByName('Point' + name); //一次移除一个对象
if (mesh) {
mesh.geometry.dispose(); //销毁对象
mesh.material.dispose();
scene.remove(mesh);
} else {
console.log("对象不存在")
}
};

单例模式

好像没什么用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import * as THREE from "three"
let { innerWidth: WIDTH, innerHeight: HEIGHT } = window
let { scene, camera, renderer } = consts, state = new State()
let b1, b2, b3, b4;

let div_WebGL = document.createElement('div')
div_WebGL.id = 'webgl-output'
document.body.appendChild(div_WebGL)
let container = document.getElementById('webgl-output')

class DrBaseScene {
static getInstance(){
if(!DrBaseScene.instance){
DrBaseScene.instance = new DrBaseScene()
}
return DrBaseScene.instance
}
constructor() {
this.animate = this.animate.bind(this) //绑定this的指向
this.init()
}
init() {
this.setScene()
this.setGUI()
this.setCamera()
this.addAxis()
this.iniPlane()
this.setLights()
this.setRender()
this.orbitControls()
this.animate()
this.windowResize()
}
setRender() {
renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: false,
});
renderer.setSize(WIDTH, HEIGHT);
renderer.setClearColor(0x220022, 1);
container.appendChild(renderer.domElement);
}
animate() {
requestAnimationFrame(this.animate);
this.render(); //需要绑定this的指向
}
car(z) {
b2.position.z = z
}
}

// 单例调用
let f1 = DrBaseScene.getInstance()
f1.car(10)

let f2 = DrBaseScene.getInstance()
f2.car(0)

let f3= DrBaseScene.getInstance()
f3.car(-10)