问题
I'm trying to make a React component that renders a three.js scene. However, whenever I try mounting the component instead of seeing any sort of scene being rendered, I just see the text [object HTMLCanvasElement]
being shown.
Here's 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 from the three npm package page and tried to convert it into a React component. What am I doing wrong that is making the scene not render?
回答1:
In order to make it work you should do the following, keep ref to your container div element:
<div style={{width:"inherit", height:"inherit", position:"absolute"}}
ref={thisNode => this.container=thisNode}
>
</div>
This will keep your canvas inside. Next thing, in componentDidMount append your 3d canvas to container.
this.container.appendChild(renderer.domElement);
You also forget to call this.renderer.render(scene,camera);
And also do not reinstantiate scene elements and renderer on every rerender. Think about this, if you will update scene with your current setup you will be recreating new scene, new renderer on every animation frame how is this could be even possible? Init your configurations in componentDidMount and then correct them in component didUpdate, also you can avoid bind by using arrow functions animate = () => {}
.
来源:https://stackoverflow.com/questions/46260176/rendering-three-js-element-in-react