在spa应用中使用threejs时, 页面unmount不会自动清除已经创建的webgl实例, 需要手动清除.
import * as React from 'react';
import {
Scene,
PerspectiveCamera,
WebGLRenderer,
BoxGeometry,
MeshBasicMaterial,
Mesh
} from 'three';
import BaseComponent from '@components/Base';
export default class HelloWorld extends BaseComponent {
container: HTMLDivElement = null;
renderer: WebGLRenderer;
componentDidMount() {
setTimeout(() => {
this.init();
}, 100);
}
componentWillUnmount() {
this.renderer.forceContextLoss();
this.renderer = null;
}
init = () => {
const { clientWidth, clientHeight } = this.container;
const scene = new Scene();
const camera = new PerspectiveCamera(75, clientWidth / clientHeight, 0.1, 1000);
this.renderer = new WebGLRenderer({
antialias: true
});
this.renderer.setSize(clientWidth, clientHeight);
this.renderer.setClearColor(0xFFFFFF, 1);
this.container.appendChild(this.renderer.domElement);
const geometry = new BoxGeometry(1, 1, 5);
const material = new MeshBasicMaterial({ color: 0xff5555 });
const cube = new Mesh(geometry, material);
camera.position.z = 5;
scene.add(cube);
const render = () => {
if (!this.renderer) {
return;
}
this.renderer.render(scene, camera);
requestAnimationFrame(render);
}
render();
}
render() {
return (
<div className="container" ref={ref => this.container = ref} />
)
}
}