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);

相关推荐
田本初2 分钟前
使用vite重构vue-cli的vue3项目
前端·vue.js·重构
ai产品老杨10 分钟前
AI赋能安全生产,推进数智化转型的智慧油站开源了。
前端·javascript·vue.js·人工智能·ecmascript
帮帮志15 分钟前
vue实现与后台springboot传递数据【传值/取值 Axios 】
前端·vue.js·spring boot
xixingzhe229 分钟前
Nginx 配置多个监听端口
服务器·前端·nginx
程序员Bears1 小时前
从零打造个人博客静态页面与TodoList应用:前端开发实战指南
java·javascript·css·html5
清风细雨_林木木1 小时前
Vue 2 项目中配置 Tailwind CSS 和 Font Awesome 的最佳实践
前端·css·vue.js
逊嘘1 小时前
【Web前端开发】CSS基础
前端·css
小宁爱Python1 小时前
深入掌握CSS Flex布局:从原理到实战
前端·javascript·css
Attacking-Coder2 小时前
前端面试宝典---webpack面试题
前端·面试·webpack
极小狐2 小时前
极狐GitLab 容器镜像仓库功能介绍
java·前端·数据库·npm·gitlab