React와 three.js 및 react-three-fiber 비교

15134 단어 reactthreejstypescript


다음 코드는 위와 동일한 출력을 보여줍니다.

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;

react-three-fiber로




pmndrs / 반응 세 섬유


🇨🇭 Three.js용 React 렌더러





반응 세 섬유









react-three-fiber는 threejs의 React renderer입니다.
상태에 반응하고 쉽게 상호 작용하며 React의 에코시스템에 참여할 수 있는 재사용 가능한 자체 포함 구성 요소를 사용하여 장면을 선언적으로 빌드합니다.
npm install three @react-three/fiber

제한이 있습니까?

None. Everything that works in Threejs will work here without exception.

일반 Threejs보다 느립니까?

No. There is no overhead. Components render outside of React. It outperforms Threejs in scale due to Reacts scheduling abilities.

Threejs에 대한 빈번한 기능 업데이트를 따라갈 수 있습니까?

Yes. It merely expresses Threejs in JSX: <mesh /> becomes new THREE.Mesh(), and that happens dynamically. If a new Threejs version adds, removes or changes features, it will be available to you instantly without depending on updates to this library.

어떻게 생겼나요?

Let's make a re-usable component that has its own state, reacts to user-input and participates in the render-loop. (live

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;

좋은 웹페이지 즐겨찾기