在uniapp中使用SVGAPlayer播放svga动画

在uniapp中使用svga,我是只需要编译为微信小程序和h5,其他端的暂时没研究。完整代码在最后
首先是微信小程序,从https://github.com/svga/svgaplayer-weapp下载svgaplayer.weapp.js,按照教程引入即可

<template>
    <canvas
      type="2d"
      style="width: 300px; height:300px;background-color: #000;"
      id="myCanvas"
      canvas-id="myCanvas"
    ></canvas>
</template>
const SVGA = require('../../utils/svga.weapp.js')
async onLoad() {
    const player = new SVGA.Player('#myCanvas')
    const parser = new SVGA.Parser('#myCanvas')
    parser.load(
      'https://qiniu.taktak.tv/spring-headlines2022/inlive.svga',
      function(value: any) {
        player.setVideoItem(value)
        player.startAnimation()
      }
    )
}

接着是h5,从https://github.com/svga/SVGAPlayer-Web下载svga.min.js,按照教程引入,运行,发现报错
在这里插入图片描述
看报错原因我们能发现,getContext这是canvas的一个api,而这个报错应该是因为没有通过#myCanvas获取到对应的canvas dom节点,我们点开Elements就会发现这是因为uniapp在编译h5的时候,会把canvas节点上的id属性给弄到uni-canvas这个节点上,这也许是为了重写多端的canvas方法
在这里插入图片描述
但是这样的话我们就没办法拿到真正的canvas节点了啊,这咋办。只能直接上暴力美学,咱们直接用js插入一个canvas dom 进去,下面附全部代码

<template>
  <view id="main">
    <!-- #ifndef H5 -->
    <canvas
      type="2d"
      style="width: 300px; height:300px;background-color: #000;"
      id="myCanvas"
      canvas-id="myCanvas"
      ref="myCanvas"
    ></canvas>
    <!-- #endif -->
  </view>
</template>
let SVGA: any = ''
// #ifndef H5
SVGA = require('../../utils/svga.weapp.js')
// #endif
// #ifdef H5
SVGA = require('../../utils/svga.min.js')
// #endif
async onLoad() {
    //#ifndef H5
    const player = new SVGA.Player('#myCanvas')
    const parser = new SVGA.Parser('#myCanvas')
    setTimeout(() => {
      parser.load(
        'https://qiniu.taktak.tv/spring-headlines2022/inlive.svga',
        function(value: any) {
          player.setVideoItem(value)
          player.startAnimation()
        }
      )
    }, 0)
    //#endif
    //#ifdef H5
    setTimeout(() => {
      const canvasList: any = document.getElementById('main')
      const canvas = document.createElement('canvas')
      canvas.width = 300
      canvas.height = 300
      canvas.style.backgroundColor = '#000'
      canvas.id = 'myCanvas'
      canvasList.appendChild(canvas)
      setTimeout(() => {
        const player = new SVGA.Player('#myCanvas')
        const parser = new SVGA.Parser('#myCanvas')
        parser.load(
          'https://qiniu.taktak.tv/spring-headlines2022/inlive.svga',
          function(value: any) {
            player.setVideoItem(value)
            player.startAnimation()
          }
        )
      }, 0)
    }, 0)
    //#endif
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值