threejs初识 | 大帅老猿threejs特训

threejs初识 | 大帅老猿threejs特训

准备工作
  • 要安装three 的 npm 模块,请在你的项目文件夹里打开终端窗口,并运行:
npm install three
  • 引入头文件
import * as THREE from 'three';
//相机轨道控制器
import {OrbitControls} from "three/examples/jsm/controls/OrbitControls";
//gltf资源加载器
import {GLTFLoader} from "three/examples/jsm/loaders/GLTFLoader";
//纹理贴图加载器
import { RGBELoader } from 'three/examples/jsm/loaders/RGBELoader';
应用
  • 创建场景
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.01, 10);
camera.position.set(0.3, 0.3, 0.5);
//渲染器
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

const controls = new OrbitControls(camera, renderer.domElement);

//添加灯光
const directionLight = new THREE.DirectionalLight(0xffffff, 0.4);
scene.add(directionLight);
  • 加载资源
let donuts;
new GLTFLoader().load('../resources/models/donuts.glb', (gltf) => {
    scene.add(gltf.scene);
    donuts = gltf.scene;

    mixer = new THREE.AnimationMixer(gltf.scene);
    const clips = gltf.animations; // 播放所有动画
    clips.forEach(function (clip) {
        const action = mixer.clipAction(clip);
        action.loop = THREE.LoopOnce;
        // 停在最后一帧
        action.clampWhenFinished = true;
        action.play();
    });

})
  • 加载场景贴图
new RGBELoader()
    .load('../resources/sky.hdr', function (texture) {
        scene.background = texture;
        texture.mapping = THREE.EquirectangularReflectionMapping;
        scene.environment = texture;
        renderer.outputEncoding = THREE.sRGBEncoding;
        renderer.render(scene, camera);
});
  • 动画方法实现
function animate() {
    requestAnimationFrame(animate);
    renderer.render(scene, camera);
    controls.update();

    if (donuts){
        donuts.rotation.y += 0.01;
    }
    if (mixer) {
        mixer.update(0.02);
    }
}

animate();
效果截图

在这里插入图片描述

结语

多学习,多动手。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值