大家好,我是梦起,明天和大家一起来学习 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),一起交流学习