Skip to content

Instantly share code, notes, and snippets.

@komietty
Last active April 13, 2022 07:51
Show Gist options
  • Save komietty/d44e2af2c5f78c467b36a5f4ab1d065e to your computer and use it in GitHub Desktop.
Save komietty/d44e2af2c5f78c467b36a5f4ab1d065e to your computer and use it in GitHub Desktop.
three.js react hooks template
import { useEffect, useRef } from "react";
import * as THREE from "three";
const App = () => {
const ref = useRef<HTMLDivElement>(null);
const scn = new THREE.Scene();
const cam = new THREE.PerspectiveCamera(75, 1, 0.1, 1000);
const rnd = new THREE.WebGLRenderer();
useEffect(() => {
let w = window.innerWidth;
let h = window.innerHeight;
cam.aspect = w / h;
cam.position.z = 5;
cam.updateProjectionMatrix();
rnd.setSize(w, h);
ref.current?.appendChild(rnd.domElement);
let cube = new THREE.Mesh(
new THREE.BoxGeometry(1, 1, 1),
new THREE.MeshBasicMaterial({ color: 0x00ff0f }),
);
scn.add(cube);
window.addEventListener("resize", () => {
let w = window.innerWidth;
let h = window.innerHeight;
cam.aspect = w / h;
cam.updateProjectionMatrix();
rnd.setSize(w, h);
}, false);
(function _() {
requestAnimationFrame(_);
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
rnd.render(scn, cam);
})();
return () => { ref.current?.removeChild(rnd.domElement) };
}, []);
return (<div ref={ref}></div>);
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment