解決: WARNING: Too many active WebGL contexts. Oldest context will be lost.

在spa應(yīng)用中使用threejs時, 頁面unmount不會自動清除已經(jīng)創(chuàng)建的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} />
    )
  }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Swift1> Swift和OC的區(qū)別1.1> Swift沒有地址/指針的概念1.2> 泛型1.3> 類型嚴謹 對...
    cosWriter閱讀 11,662評論 1 32
  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫、插件、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 15,358評論 4 61
  • 第一部分 HTML&CSS整理答案 1. 什么是HTML5? 答:HTML5是最新的HTML標(biāo)準(zhǔn)。 注意:講述HT...
    kismetajun閱讀 28,817評論 1 45
  • 如果剛吃過糖,馬上再去吃蘋果,你會覺得蘋果一點兒也不甜。但如果你剛吃完很苦的藥,再去吃同一個蘋果就會覺得很...
    西樓風(fēng)雨閱讀 323評論 0 0
  • 今天早上出小區(qū)大門時,看見旁邊門市前搭了很多紅色的大雨傘,好多人排隊像是搶夠什么東西。我走進一看,是永輝在小區(qū)門口...
    傲雪_352a閱讀 257評論 1 0

友情鏈接更多精彩內(nèi)容