- lottie json 文件注意事项
- lottie文件版本建议使用5.7及以下,否则可能会出现真机不显示/显示出错的问题
- lottie文件导出需要勾选 Convert expressions to keyframes 将表达式转为关键帧,因为小程序里不支持使用 eval 等动态执行脚本的能力。 小程序中使用 lottie 动画 | 踩坑经验分享
- lottie在线预览
yarn add lottie-miniprogram
uniapp
<script lang="ts" setup>
import lottie from 'lottie-miniprogram';
import { onMounted, getCurrentInstance } from 'vue'
import lottieJson from '@/static/lottie/lottie.json'
const _this = getCurrentInstance()!;
const Size = {
width:300,
height:300
}
const init = async () => {
// 组件下需要通过组件实例使用
_this.ctx.createSelectorQuery()// wx.createSelectorQuery()
.select('#lottie')
.node(async res => {
const canvas = res.node;
const context = canvas.getContext('2d');
// 处理真机显示模糊
const dpr = wx.getSystemInfoSync().pixelRatio;
canvas.width = Size.width * dpr;
canvas.height = Size.height * dpr;
context.scale(dpr, dpr);
lottie.setup(canvas);
const ani = lottie.loadAnimation({
loop: true,
autoplay: true,
animationData: lottieJson,
rendererSettings: {
context
}
});
// 播放部分动画
// ani.addEventListener("DOMLoaded", () => {
// ani.playSegments([0, 50], true);
// });
})
.exec();
}
onMounted(async () => {
init()
})
</script>
<template>
<view class="lottie-view">
<canvas
id="lottie"
type="2d"
class="lottie"
/>
</view>
</template>
掘金AI优化版(未验证)
<script lang="ts" setup>
import lottie from 'lottie-miniprogram';
import { onMounted, getCurrentInstance } from 'vue'
import lottieJson from '@/static/lottie/lottie.json'
// 获取当前组件实例
const _this = getCurrentInstance()!;
// 定义动画配置
const animationConfig = {
width: 300,
height: 300,
loop: true,
autoplay: true
};
// 处理canvas尺寸和清晰度
const setupCanvas = (canvas: any) => {
const dpr = wx.getSystemInfoSync().pixelRatio;
canvas.width = animationConfig.width * dpr;
canvas.height = animationConfig.height * dpr;
const context = canvas.getContext('2d');
context.scale(dpr, dpr);
return context;
};
// 初始化动画
const initAnimation = async (canvas: any, context: any) => {
try {
lottie.setup(canvas);
const ani = lottie.loadAnimation({
loop: animationConfig.loop,
autoplay: animationConfig.autoplay,
animationData: lottieJson,
rendererSettings: {
context
}
});
return ani;
} catch (error) {
console.error('动画加载失败:', error);
return null;
}
};
// 初始化函数
const init = async () => {
_this.ctx.createSelectorQuery()
.select('#lottie')
.node(async res => {
if (!res.node) {
console.error('未找到canvas元素');
return;
}
const canvas = res.node;
const context = setupCanvas(canvas);
const ani = await initAnimation(canvas, context);
if (ani) {
// 这里可以添加更多动画控制逻辑,例如播放动画
// ani.addEventListener("DOMLoaded", () => {
// ani.playSegments([0, 50], true);
// });
}
})
.exec();
};
// 组件挂载后初始化
onMounted(async () => {
init()
})
</script>
<template>
<view class="lottie-view">
<canvas
id="lottie"
type="2d"
class="lottie"
/>
</view>
</template>