【问题标题】:Rendering three.js element in React?在 React 中渲染 three.js 元素?
【发布时间】:2018-02-25 20:41:45
【问题描述】:

我正在尝试制作一个渲染 three.js 场景的 React 组件。但是,每当我尝试安装组件而不是看到正在渲染的任何场景时,我只会看到文本 [object HTMLCanvasElement] 正在显示。

这是我的组件:

import React from 'react';
import * as THREE from 'three';

class Cube extends React.Component {

    constructor() {
        super();
        this.animate = this.animate.bind(this);
        this.scene = new THREE.Scene();
        this.geometry = new THREE.BoxGeometry(200, 200, 200);
        this.material = new THREE.MeshBasicMaterial({
            color: 0xff0000,
            wireframe: true
        });
        this.mesh = new THREE.Mesh(this.geometry,this.material);
        this.scene.add(this.mesh);
        this.renderer = null;
        this.camera = null;
    }

    render() {
        if (typeof window !== 'undefined') {
            this.camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 10000);
            this.camera.position.z = 1000;
            this.renderer = new THREE.WebGLRenderer();
            this.renderer.setSize(window.innerWidth, window.innerHeight);
            return (
                <div dangerouslySetInnerHTML={{__html: this.renderer.domElement}}></div>
            );
        } else {
            return null;
        }
    }
}

export default Cube;

我从three npm package page 获得代码并尝试将其转换为 React 组件。我做错了什么导致场景无法渲染?

【问题讨论】:

    标签: reactjs three.js


    【解决方案1】:

    为了使其正常工作,您应该执行以下操作,将 ref 保留到您的容器 div 元素:

    <div style={{width:"inherit", height:"inherit", position:"absolute"}} 
      ref={thisNode => this.container=thisNode}
    >    
    </div>  
    

    这将使您的画布保持在里面。接下来,在 componentDidMount 中将 3d 画布附加到容器中。

    this.container.appendChild(renderer.domElement);
    

    你也忘了打this.renderer.render(scene,camera); 并且不要在每次重新渲染时重新实例化场景元素和渲染器。想一想,如果您将使用当前设置更新场景,您将在每个动画帧上重新创建新场景、新渲染器,这怎么可能?在 componentDidMount 中初始化你的配置,然后在组件 didUpdate 中更正它们,你也可以通过使用箭头函数 animate = () =&gt; {} 来避免绑定。

    【讨论】:

    • 在 render() 函数中渲染东西不是反应的全部意义。有没有更清洁的方法可以做到这一点?
    • 你是对的,渲染,但不是从头开始创建,this.renderer = new THREE.WebGLRenderer();将创建全新的 webglrenderer,这是一个附加了场景和相机的大对象,为了渲染你应该调用这个对象的 METHOD 方法,而不是在每一帧上从头开始重新创建这个巨大的对象
    • 也渲染threejs场景除了将canvas连接到dom中的容器之外,与渲染dom对象无关,由webglrenderer确定在您的canvas上绘制的内容
    猜你喜欢
    • 1970-01-01
    • 2018-08-07
    • 1970-01-01
    • 1970-01-01
    • 2012-05-07
    • 2017-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多