react 中three.js 模型渲染

    npm install three

import * as THREE from "three";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";
const mountRef = useRef(null);
useEffect(() => {

     // 创建渲染器  
    const renderer = new THREE.WebGLRenderer(); 
    const width = mountRef.current.clientWidth;  
    const height = mountRef.current.clientHeight; 
    // 创建场景  
    const scene = new THREE.Scene();  
// 创建相机  
    const camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 1000);  
    camera.position.z = 125;  
    camera.rotation.x=-70
    camera.position.y=150

    // 更新相机的矩阵
    camera.updateMatrix();

    // 修改fov
    camera.scale.set(1.3,1.5,1.2);
    camera.fov = 100; // 设置新的fov为90度
    camera.updateProjectionMatrix(); // 更新投影矩阵
     
    renderer.setSize(width, height);  
    mountRef.current.appendChild(renderer.domElement);  
    renderer.setClearColor(0x000000, 0); //画布背景为透明,
   
// 创建加载器  
    const loader = new GLTFLoader();
   const ambientLight = new THREE.AmbientLight(0xffffff, 2);
    scene.add(ambientLight);
    loader.load(  
      './factory.glb', // 模型的URL  
      function (gltf) {  
        model = gltf.scene;
        scene.add(model); // 将加载的模型添加到场景中  
        
        
      }
    );  
      // 渲染循环  
  const animate = (event) => {  
      
    renderer.render(scene, camera); 
    TWEEN.update(); // 更新动画状态
    requestAnimationFrame(animate);
  };  
  
  animate(); 
})

return(
    
)

这里有个问题是模型放的文件夹,在我这引用的时候,我是放到了public文件下,引用的时候就是./  放在其他文件下 会有问题。

模型必须给光源,要不然模型是黑的

 // 添加光源

    // AmbientLight 环境光 环境光环境光是最简单的一种光源,它均匀地照亮场景中的所有物体,没有方向性。使用环境光可以为场景提供基础亮度,但它不能产生阴影,也不提供方向性的光照效果。

    //DirectionalLight 方向光 方向光模仿太阳光,从一个方向均匀地照亮场景,可以产生硬阴影。为了照亮整个模型,你可以将方向光的方向设置为指向模型,通常是从上方或侧面照射

    //HemisphereLight 半球光 半球光提供来自两个方向的光照,通常用于模拟天空和地面的光照。它可以为场景提供更为自然的基础照明。

    //PointLight(点光源) 或 SpotLight(聚光灯) 这两种光源可以照亮模型的大部分区域,但是它们的效果通常受限于光源的位置和范围。为了照亮整个模型,你可能需要多个光源,或者调整光源的位置和范围。

    // const light = new THREE.SpotLight(0xffffff, 2);

    // light.position.set(10, 10, 10).normalize();

    // scene.add(light);

你可能感兴趣的:(react,javascript,react.js,前端)