Three.js flexbox react (stack #59657140)
For stack question: https://stackoverflow.com/questions/59657140
by Chris Brown
HTML
<!--<script src="https://unpkg.com/[email protected]/build/three.js"></script>-->
<script src="https://rawgit.com/mrdoob/three.js/master/build/three.min.js"></script>
<div id="app"></div>
CSS
body {
background: #20262E;
padding: 0px;
}
#app {
background: #fff;
height: 100vh;
}
.flex-row-container {
display: flex;
flex-flow: row;
height: 100%;
width: 100%;
}
.sidebar {
display: block;
flex: 0 0 150px;
background-color: #555;
margin: 3px 4px 3px 4px;
box-sizing: border-box;
border: 1px solid #888;
}
.viewport {
flex: 1 1 auto;
overflow: hidden;
}
React
class Viewport extends React.Component {
componentDidMount() {
const width = this.mount.clientWidth;
const height = this.mount.clientHeight;
window.addEventListener("resize", this.handleWindowResize);
// setup scene
this.scene = new THREE.Scene();
//setup camera
this.camera = new THREE.PerspectiveCamera( 75, width / height, 0.1, 1000 );
this.camera.position.set( 0, 5, 400 );
// setup rendering
this.renderer = new THREE.WebGLRenderer({ antialias: true });
this.renderer.setClearColor('#666666');
this.renderer.setSize(width, height, false);
this.mount.appendChild(this.renderer.domElement);
// setup geo
const geometry = new THREE.BoxGeometry(200, 200, 200);
const material = new THREE.MeshBasicMaterial({ color: '#433F81' });
this.cube = new THREE.Mesh(geometry, material);
this.scene.add(this.cube);
this.renderer.render(this.scene, this.camera);
this.animate();
}
componentWillUnmount() {
window.removeEventListener("resize", this.handleWindowResize);
this.mount.removeChild(this.renderer.domElement);
}
handleWindowResize = () => {
const width = this.mount.clientWidth;
const height = this.mount.clientHeight;
this.camera.aspect = width / height;
this.camera.updateProjectionMatrix();
this.renderer.setSize(width, height, false);
this.renderer.render(this.scene, this.camera);
}
animate = () => {
requestAnimationFrame(this.animate);
this.cube.rotation.x += 0.005;
this.cube.rotation.y += 0.01;
this.renderer.render(this.scene, this.camera);
}
render() {
return (
<div className="viewport" ref={(mount) => { this.mount = mount }} />
);
}
}
class MyApp extends React.Component {
constructor(props) {
super(props)
}
render() {
return (
<div className="flex-row-container">
<div className="sidebar"></div>
<Viewport />
</div>
)
...