写在前面

本文用vue+threejs写物体动画:物体缩放动画。

实现原理:让缩放值根据秒数的增加呈函数式变化,以达到动画展示的效果。

下面是演示gif:

vue+threejs写物体动画之物体缩放动画效果

代码说明

<template>
<div class="item">
<div id="THREE42"></div>
</div>
</template>
import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
import { DRACOLoader } from "three/examples/jsm/loaders/DRACOLoader.js";
mounted() {
this.initThreejs();
},
initThreejs() {
let camera, scene, renderer;
let mesh;
let clock = new THREE.Clock();
const dracoLoader = new DRACOLoader();
dracoLoader.setDecoderPath("js/libs/draco/");
dracoLoader.setDecoderConfig({ type: "js" });
init();
function init() {
// 创建场景
scene = new THREE.Scene();
scene.background = new THREE.Color(0x000000); // 设置场景背景颜色
// 创建灯光
const light = new THREE.DirectionalLight(0xffffff); // 平行光
light.position.set(0.5, 1.0, 0.5).normalize(); // 设置平行光的方向,从(0.5, 1.0, 0.5)->target一般(0, 0, 0)
scene.add(light); // 将灯光添加到场景中
// 创建相机
camera = new THREE.PerspectiveCamera(
35,
(window.innerWidth - 201) / window.innerHeight,
1,
500
); // 透视相机
camera.position.x = 0.5;
camera.position.y = 0.5; // 设置相机的位置
camera.position.z = 1.8;
scene.add(camera); // 将相机添加到场景中
// 创建渲染器
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.outputEncoding = THREE.sRGBEncoding;
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth - 201, window.innerHeight);
document.getElementById("THREE42").appendChild(renderer.domElement);
// 创建轨道控制器
const controls = new OrbitControls(camera, renderer.domElement);
controls.addEventListener("change", render);
controls.update();
// 创建地面
const ground = new THREE.Mesh(
new THREE.BoxGeometry(1, 0.0015, 1),
new THREE.MeshPhongMaterial({
color: 0x999999,
depthWrite: false,
transparent: true,
opacity: 1,
})
);
ground.receiveShadow = true;
scene.add(ground);
document.addEventListener("pointerdown", animate); // 监听鼠标、手指落下
//  加载模型
dracoLoader.load("/models/models/draco/bunny.drc", function (geometry) {
geometry.computeVertexNormals();
const material = new THREE.MeshStandardMaterial({ color: 0xffffff });
mesh = new THREE.Mesh(geometry, material);
mesh.castShadow = true;
mesh.receiveShadow = true;
scene.add(mesh);
dracoLoader.dispose();
render();
});
}
function animate() {
requestAnimationFrame(animate);
const elapsed = clock.getElapsedTime();
// getElapsedTime 获取自时钟启动后的秒数
// 让缩放值根据秒数的增加呈函数式变化,以达到动画展示的效果
let scale = 1 + 0.5 * Math.sin(2 * elapsed);
mesh.scale.set(scale, scale, scale);
render();
}
function render() {
renderer.render(scene, camera);
}
},

写在最后

以上就是所有的代码和说明。

到此这篇关于vue+threejs写物体动画之物体缩放动画效果的文章就介绍到这了,更多相关vue+threejs物体缩放动画内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!