Skip to content

Instantly share code, notes, and snippets.

@williamsiuhang
Created December 26, 2019 07:33
Show Gist options
  • Save williamsiuhang/e2705369fdb93d427a71ce9a3eb4fb55 to your computer and use it in GitHub Desktop.
Save williamsiuhang/e2705369fdb93d427a71ce9a3eb4fb55 to your computer and use it in GitHub Desktop.
Simple React Three js scene component
import React from 'react';
import * as THREE from 'three';
import { TrackballControls } from 'three/examples/jsm/controls/TrackballControls.js';
class Scene extends React.Component {
constructor(props) {
super(props)
this.animate = this.animate.bind(this);
this.addCube = this.addCube.bind(this);
this.initializeCamera = this.initializeCamera.bind(this);
this.initializeOrbits = this.initializeOrbits.bind(this);
}
componentDidMount() {
const width = window.innerWidth;
const height = window.innerHeight;
this.scene = new THREE.Scene();
this.camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 1000);
this.renderer = new THREE.WebGLRenderer({ antialias: true });
this.controls = new TrackballControls(this.camera, this.renderer.domElement);
this.renderer.setSize(width, height);
this.mount.appendChild(this.renderer.domElement);
this.initializeOrbits();
this.initializeCamera();
this.scene.background = new THREE.Color(0x0f3443)
const geometry = new THREE.BoxGeometry( 1, 1, 1 );
const material = new THREE.MeshBasicMaterial( { color: 0xFF00FF } );
this.cube = new THREE.Mesh( geometry, material );
this.scene.add( this.cube );
this.animate();
}
componentWillUnmount() {
cancelAnimationFrame(this.frameId);
this.mount.removeChild(this.renderer.domElement);
}
initializeOrbits() {
this.controls.rotateSpeed = 1.0;
this.controls.zoomSpeed = 1.2;
this.controls.panSpeed = 0.8;
}
initializeCamera() {
this.camera.position.x = 0;
this.camera.position.y = 0;
this.camera.position.z = 4;
}
animate() {
this.frameId = window.requestAnimationFrame(this.animate);
this.renderer.render(this.scene, this.camera);
}
addCube(cube) {
this.scene.add(cube);
}
render() {
return (
<div>
<div
id="boardCanvas"
ref={mount => { this.mount = mount }}
/>
</div>
)
}
}
export default Scene;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment