这是一篇久违的开发记录blog。
过程
在小程序开发上,要想在视觉上取得一定的创意,靠其内建的动画机制,麻烦至极,而单纯使用css动画,制作难度也没好到哪里去,且可操控性较差。综上,使用lottie的动画是一个非常不错的选择,等于开放了动画制作能力,就可以寻求专业动画工作者的帮助。这呼声已经长久存在了,至少在2019年,就有人在微信的开放社区分享类似功能的帖子。小程序开发组提供了官方的lottie支持,不过我们本次要在使用TaroJS,用TS开发,在小程序内使用Lottie动画的功能,步骤略有不同,有几个小坑要填。
- 安装lottie-miniprogram
1
| pnpm i lottie-miniprogram
|
lottie-miniprogram比较良心地支持TS,👍
- 找个喜欢的lottie动画
From here, 下载lottie原始json格式,然后放到你自己的远程文件存储即可。
- 新建React组件,代码整体如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
| import { FC, useEffect } from 'react' import lottie from 'lottie-miniprogram' import { View } from '@fower/taro' import { Canvas } from '@tarojs/components' import Taro from '@tarojs/taro'
export type LottieCompProps = {} const LottieComp: FC<LottieCompProps> = ({}) => { useEffect(() => { Taro.downloadFile({ url: 'https://storage.writeitdown.site/b9/coffee-cup-3.json', complete: (downloaded: any) => { Taro.getFileSystemManager().readFile({ filePath: downloaded.tempFilePath, success: (res) => { const buffer: ArrayBuffer = res.data as ArrayBuffer const unit8Arr = new Uint8Array(buffer) const encodedString = String.fromCharCode.apply(null, unit8Arr) const lottieData = JSON.parse(encodedString) wx.createSelectorQuery() .select('#canvas') .node((res) => { const canvas = res.node const _ctx = canvas.getContext('2d') const dpr = Taro.getSystemInfoSync().pixelRatio canvas.width = 400 * dpr canvas.height = 200 * dpr _ctx.scale(dpr,dpr) lottie.setup(canvas) lottie.loadAnimation({ animationData: lottieData, rendererSettings: { context: _ctx, }, loop: true, autoplay: true, }) }) .exec() }, }) }, }) }, []) return ( <View column toCenter> <Canvas id="canvas" type="2d" /> </View> ) } export default LottieComp
|
未完待续
即便这样打包后,lottie仍然会让对应page体积过大,会超过单个page上限,稍后可以使用subpackage进行分割
以微信生态圈为代表的社区里,你经常可以看到“我已经解决了”的自问自答,不列举具体原因,然后再无音信,究其原因,可能是生态恶化导致,人人自危,难以为善,明明知道是粪池,也要来分一杯。