celsius的个人博客

星星之火可以燎原

0%

在uniapp中使用SVGAPlayer播放svga动画

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

1
2
3
4
5
6
7
8
<template>
<canvas
type="2d"
style="width: 300px; height:300px;background-color: #000;"
id="myCanvas"
canvas-id="myCanvas"
></canvas>
</template>
1
2
3
4
5
6
7
8
9
10
11
12
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 进去,下面附全部代码

1
2
3
4
5
6
7
8
9
10
11
12
13
<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>
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
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
}