调研动画库Lottie在微信小程序中的应用

1.安装

第一步: 若项目中没有package.json文件 无法安装,可以通过 npm init初始化一个package.json文件

lottie-miniprogram官网

第二步: 安装 npm install --save lottie-miniprogram

第三步: 微信开发者工具——工具 -> 构建npm

2.使用

2.1 在wxml中定义画布

.wxml文件
 <canvas id="canvas" type="2d"></canvas>

2.2 在.js文件中获取并执行动画效果

2.2.1 本地JSON文件格式动画

转换成js文件,export default json内容
animationData:data,

import data from  '../../assets/data.js'
import lottie from 'lottie-miniprogram'

  onLoad() {
    wx.createSelectorQuery().select('#canvas').node(res => {
      const canvas = res.node
      const context = canvas.getContext('2d')
      lottie.setup(canvas)//要执行动画,必须调用setup,传入canvas对象
      lottie.loadAnimation({//微信小程序给的接口
        loop: true,//是否循环播放(选填)
        autoplay: true,//是否自动播放(选填)
        animationData:data, // 读取本地json文件  !!!!!
        rendererSettings:{
          context//es6语法:等同于context:context(必填)
        }       
      })
    }).exec()
  }

2.2.2 cdn上面存储JSON格式动画

path:'https://xxxx.com/animation.json'

  onLoad() {
    wx.createSelectorQuery().select('#canvas').node(res => {
      const canvas = res.node
      const context = canvas.getContext('2d')
      lottie.setup(canvas)//要执行动画,必须调用setup,传入canvas对象
      lottie.loadAnimation({//微信小程序给的接口
        loop: true,//是否循环播放(选填)
        autoplay: true,//是否自动播放(选填)
  	    path:'https://xxxx.com/animation.json',//读取json包网络链接  !!!!!!
        rendererSettings:{
          context//es6语法:等同于context:context(必填)
        }       
      })
    }).exec()
  }

2.2.3 注意

  • 在自定义组件或包含自定义组件的页面中,应使用 this.createSelectorQuery() 来代替 wx.createSelectorQuery(),不然返回的res为null,会报错
  • 若获取canvas画布中res.node获取失败时,比如只返回nodeCanvasType为"",没有返回node信息,可以将canvas上增加 type=“2d”

文章参考

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值