Taro2开发微信小程序中使用Lottie动画库 + 解决画面模糊、有锯齿

1,085 阅读1分钟

lottie相关库

lottie-miniprogram官方小程序文档中提供的用于在小程序中使用的lottie库。

Taro2 实现

  1. 通过 npm 安装:
npm install --save lottie-miniprogram
  1. 使用 Canvas 组件进行适配
<Canvas id=“canvas” type="2d" />
  1. 使用 Lottie 接口
import lottie from 'lottie-miniprogram'

Taro.createSelectorQuery().select('#canvas').node((res: any) => {
  const canvas = res.node;
  const context = canvas.getContext('2d');
  lottie.setup(canvas);
  this.ani = lottie.loadAnimation({
    rendererSettings: {
      context
    },
    loop: true,
    autoplay: true,
    animationData: require('./lottie/test.json')
  });
}).exec()

暂停动画

 pause() {
    this.ani.pause()
  }

播放动画

 pause() {
    this.ani.pause()
  }

目前微信小程序只提供了两个接口

lottie.setup(canvas)

在任何 lottie 接口调用之前,需要传入 canvas 对象

lottie.loadAnimation(options)

与原来的 loadAnimation 有些不同,支持的参数有:

*   loop // 循环播放
*   autoplay //自动播放
*   animationData // 动画数据
*   path //(只支持网络地址)
*   rendererSettings.context //(必填)

使用时画面模糊、有锯齿

问题的原因

retina屏幕的高分辨率导致了canvas画出的图像模糊、失真、锯齿,只需要获取到当前设备的devicePixelRatio,然后将画布和宽高、canvas的上下文同时缩放devicePixelRatio倍(其实就是放大devicePixelRatio倍)即可

解决方法

  1. 获取设备像素比

我这里使用微信 wx.getSystemInfo(Object object) 获取系统信息

wx.getSystemInfo({
  success: (res) => {
    this.pixelRatio = res.pixelRatio
  }
})
  1. 放大 devicePixelRatio 倍
Taro.createSelectorQuery().select('#canvas').node((res: any) => {
  const canvas = res.node;
  const context = canvas.getContext('2d');
  //-------- 放大 --------
  if (this.pixelRatio) {
    context.scale(this.pixelRatio, this.pixelRatio)
    canvas.width = 360* this.pixelRatio
    canvas.height = 180* this.pixelRatio
  }
  //-------- 结束 --------
  lottie.setup(canvas);
  lottie.loadAnimation({
    rendererSettings: {
      context
    },
    loop: true,
    autoplay: true,
    animationData: require('./lottie/test.json')
  });
}).exec()