react 中three.js 模型渲染

npm install three

javascript 复制代码
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(
    <div ref={mountRef} style={{width:'100%',height:'100%',backgroundColor: "transparent"}}></div>
)

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

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

// 添加光源

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

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

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

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

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

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

// scene.add(light);

相关推荐
Rverdoser8 分钟前
unocss 一直热更新打印[vite] hot updated: /__uno.css
前端·css
Bang邦25 分钟前
使用nvm管理Node.js多版本
前端·node.js·node多版本管理
podoor29 分钟前
wordpress不同网站 调用同一数据表
前端·wordpress
LJ小番茄1 小时前
Vue 常见的几种通信方式(总结)
前端·javascript·vue.js·html
黑狼传说1 小时前
前端项目优化:极致最优 vs 相对最优 —— 深入探索与实践
前端·性能优化
장숙혜1 小时前
前端-CDN的理解及CDN一些使用平台
前端
FakeOccupational2 小时前
nodejs 007:错误npm error Error: EPERM: operation not permitted, symlink
前端·npm·node.js
奶糖 肥晨2 小时前
react是什么?
前端·react.js·前端框架
亦舒.2 小时前
JSDelivr & NPM CDN 国内加速节点
前端·npm·node.js
代码搬运媛2 小时前
code eintegrity npm err sha512
前端·npm·node.js