从甜甜圈到数字孪生| 大帅老猿threejs特训

大家好,我是梦起,今天和大家一起来学习ThreeJs,早日实现ThreeJs自由。

首先,咱们需要安装threejs
npm i three
然后,引入three
import * as THREE from 'three';
然后开始创建场景/相机/渲染器
// 定义场景
var scene = new THREE.Scene()
// 定义相机
var camera = new THREE.PerspectiveCamera(75,window.innerHeight/window.innerWidth,0.01,10)
// 定义渲染器
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
将渲染器添加到页面
document.body.appendChild(renderer.domElement);
设置一下相机位置
camera.position.set(0.3, 0.3, 0.5);
加个three自带的鼠标控制
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
const controls = new OrbitControls(camera, renderer.domElement);
加点环境光,并将它加载进场景
const directionLight = new THREE.DirectionalLight(0xffffff, 0.4);
scene.add(directionLight);
加载咱们的甜甜圈模型(自己做的很PS:不可能,绝对不可能,还是用胖达老师做的
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();

是不是就完美了。效果图如下:

最后

加入猿创营 (v:dashuailaoyuan),一起交流学习

你可能感兴趣的:(前端three.js)