在 React 中渲染 Three.js 元素?

2024-04-22

我正在尝试制作一个渲染 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;

我从以下位置得到了代码三个npm包页面 https://www.npmjs.com/package/three并尝试将其转换为 React 组件。我做错了什么导致场景无法渲染?


为了使其工作,您应该执行以下操作,保留对容器 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 = () => {}.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 React 中渲染 Three.js 元素? 的相关文章

随机推荐