The following codes show the same output like above.
With threejs
import React from 'react';
import './App.css';
import * as THREE from 'three';
function App() {
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.innerHTML = '';
document.body.appendChild(renderer.domElement);
const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshBasicMaterial({
color: 'blue',
});
camera.position.z = 5;
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
const animate = () => {
requestAnimationFrame(animate);
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render(scene, camera);
}
animate();
window.addEventListener('resize', ()=>{
renderer.setSize(window.innerWidth, window.innerHeight);
camera.aspect = window.innerWidth/window.innerHeight;
camera.updateProjectionMatrix();
})
return(
null
);
}
export default App;
With react-three-fiber
pmndrs / react-three-fiber
🇨🇠A React renderer for Three.js
@react-three/fiber
react-three-fiber is a React renderer for threejs.
Build your scene declaratively with re-usable, self-contained components that react to state, are readily interactive and can participate in React's ecosystem.
npm install three @types/three @react-three/fiber
Does it have limitations?
None. Everything that works in Threejs will work here without exception.
Is it slower than plain Threejs?
No. There is no overhead. Components render outside of React. It outperforms Threejs in scale due to React's scheduling abilities.
Can it keep up with frequent feature updates to Threejs?
Yes. It merely expresses Threejs in JSX, <mesh />
dynamically turns into new THREE.Mesh()
. If a new Threejs version adds, removes or changes features, it will be available to you instantly without depending on updates to this library.
What does it look like?
Let's make a re-usable component that has its own state, reacts to user-input and participates in the render-loop. (live demo |
react-three-fiber has components that allow us to use without creating each instance for scene, camera, material, mesh etc.
import React, { useRef } from 'react';
import './App.css';
import { Canvas, useFrame } from 'react-three-fiber';
const Box = () => {
const ref = useRef<THREE.Mesh>();
useFrame((state) => {
// console.log(state);
if(ref.current !== undefined) {
ref.current.rotation.x = ref.current.rotation.y += 0.01;
}
});
return(
<mesh ref={ref}>
<boxBufferGeometry />
<meshBasicMaterial color="blue" />
</mesh>
);
}
function App() {
return(
<div style={{ height:'100vh', width:'100vh'}}>
<Canvas style={{ background: 'black'}}>
<Box />
</Canvas>
</div>
);
}
export default App;
Top comments (0)