美文网首页
解决: WARNING: Too many active Web

解决: WARNING: Too many active Web

作者: 朝西的生活 | 来源:发表于2019-04-01 17:24 被阅读0次

    在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} />
        )
      }
    }
    

    相关文章

      网友评论

          本文标题:解决: WARNING: Too many active Web

          本文链接:https://www.haomeiwen.com/subject/hmbcpqtx.html