1 版本
vuecli:4.5.7
three.js:0.131.0
2 使用worker-loader
2.1 安装worker-loader
npm install worker-loader --save-dev
2.2 vue.config.js中进行配置
chainWebpack: config => {
// 设置解析以worker.js 结尾的文件使用worker-loader 解析
config.module.rule('worker-loader').test(/\.worker\.js$/).use('worker-
loader').loader('worker-loader').end();
config.module.rule('js').exclude.add(/\.worker\.js$/);
}
3 创建Animate.worker.js用于不断更新模型位置信息
注意:必须以worker.js 结尾的文件才能使用worker-loader 解析
// animate.worker.js 文件
import * as THREE from "three/build/three.module.js";
onmessage = function (e) {
console.info('animate.worker', e.data);
const posArry = e.data; // e.data用于存储移动路线的数组
const path = new THREE.LineCurve(posArry[0], posArry[1]);
let curIndex = 0;
setInterval(function () {
let curPos, rotateY;
curPos = calPosition(path,curIndex); //用于计算当前模型的位置
rotateY = calHeading(path,curIndex); //用于计算当前模型的朝向
curIndex = curIndex + 1;
if (curIndex === 1000) {
curIndex = 0;
}
postMessage({
curPos,
rotateY
});
}, 1000 / 30);
}
4 前端传递参数使用Animate.worker.js
// 前端vue文件
import animateWorker from "@/assets/js/three/hjq/worker/animate.worker.js";
// 封装方法:加载GLTF模型
loadGLTF(this_.mUrls.bird, (gltf) => {
const mesh = gltf.scene;
// path:路线数组
const path = [
[108.566, 40.688],
[107.53, 40.551],
];
// 封装方法:设置模型的初始位置
setLocation(mesh, [path[0][0], 15, path[0][1]], [0, 0, 0], [0.1, 0.1, 0.1]);
this_.mScene.add(mesh);
// 解析gltf模型的动画
this_.mBirdMixer = new THREE.AnimationMixer(mesh);
this_.mBirdMixer.clipAction(gltf.animations[0]).play();
if (window.Worker) {
// animateWorker对应开头import的animate.worker.js
const cowWorker = new animateWorker();
cowWorker.postMessage(path);
cowWorker.onmessage = function (e) {
mesh.position.set(e.data.curPos.x, 15, e.data.curPos.y);
mesh.rotation.set(0, e.data.rotateY + Math.PI * 1.1, 0);
};
}
});