Rendering a three.js element in React?

I am trying to create a React component that displays a three.js scene. However, whenever I try to install the component instead of seeing any visualization of the scene, I just see the text [object HTMLCanvasElement] that is displayed.

Here is my component:

 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; 

I got the code for three pages of the npm package and tried to convert it to a React component. What am I doing wrong, which makes the scene non-rendering?

+3
reactjs
source share
1 answer

To make it work, you should do the following: save the link to the container div element:

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

This will keep your canvas inside. Then, in the DidMount component, add your 3D canvas to the container.

 this.container.appendChild(renderer.domElement); 

You will also forget to call this.renderer.render(scene,camera); And also do not restore the elements of the scene and rendering on each player. Think about it, if you update the scene with your current setting, you will recreate a new scene, a new renderer on each animation frame, how can this even be possible? Start your configurations in the DidMount component, and then correct them in the didUpdate component, you can also avoid binding using the arrow functions animate = () => {} .

+4
source share

All Articles