引入之后小程序包太大了, 不想分包,所以改成css实现,把使用lottie的过程记录下来,后面可能会用到
- uniapp创建后没有package.json文件,在根目录打开控制台输入
npm init -y
- 这时候就有package.json了,这个以我尝试的结果来看,其实有没有无所谓,有的话,编辑器能识别类库
- 安装类库,我的版本是1.1.0
npm i lottiejs-miniapp --save
- 代码
<template>
<view v-show="show" :class="{loading: true, 'full-screen': fullScreen }" :style="{ 'background-color': backgroundColor }">
<canvas ref="loading-canvas" id="loading-canvas" canvas-id="loading-canvas" class="lottiejs-canvas" type="2d"></canvas>
</view>
</template>
// 引入类库
import * as lottie from 'lottiejs-miniapp'
// 引入lottie的json文件
import animationData from './open-loading.json'
export default {
name: 'Loading',
data() {
return {}
},
props: {
show: {
type: Boolean,
default: false
},
fullScreen: {
type: Boolean,
default: false
},
backgroundColor: {
type: String,
default: ''
}
},
watch: {
},
methods: {
createLoading() {
// 一定要加上in(this),网上找的案例没有加in(this),获取到的res是null
uni.createSelectorQuery().in(this).select('#loading-canvas').fields({
node: true,
size: true
}).exec(res => {
console.log('res', res)
const canvas = res[0].node;
const ctx = canvas.getContext('2d');
const dpr = uni.getSystemInfoSync().pixelRatio;
canvas.width = res[0].width * dpr;
canvas.height = res[0].height * dpr;
ctx.scale(dpr, dpr);
lottie.setup(canvas);
lottie.loadAnimation({
loop: true,
autoplay: true,
// animationData和path选一个就行
animationData: animationData,
// path: 'https://labs.nearpod.com/bodymovin/demo/markus/halloween/markus.json',
// path: 'https://www.lottiejs.com/wp-content/uploads/2022/01/83351-taking-the-duggy-out.json',
rendererSettings: {
context: ctx,
},
});
});
}
},
computed: {
},
onReady() {
},
mounted() {
this.createLoading()
},
created() { }
}
- 顺带附上一个下载lottie动画的网站LottieFiles: Download Free lightweight animations for website & apps.