React 使用 three.js 加载 gltf 3D模型 | three.js 入门
import React, { useRef, useEffect } from 'react';
import * as THREE from 'three';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
const ModelViewer = () => {
const sceneRef = useRef();
let scene, camera, renderer, model, controls;
const init = () => {
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
controls = new OrbitControls(camera, renderer.domElement);
const loader = new GLTFLoader();
loader.load('path/to/your/model.gltf', (gltf) => {
model = gltf.scene;
scene.add(model);
});
camera.position.z = 5;
animate();
}
const animate = () => {
requestAnimationFrame(animate);
renderer.render(scene, camera);
controls.update();
}
useEffect(() => {
init();
return () => {
// 清理工作,比如移除动画帧请求等
};
}, []);
return (
<div ref={sceneRef} />
);
};
export default ModelViewer;
这段代码展示了如何在React组件中初始化three.js场景、添加3D模型、设置摄像机、渲染器和轨道控制器,并在组件挂载时开始动画循环。这是学习three.js和React结合使用的一个很好的起点。
评论已关闭