SVGA 是一种跨平台的开源动画格式,同时兼容 iOS / Android / Web。SVGA 除了使用简单,性能卓越,同时让动画开发分工明确,各自专注各自的领域,大大减少动画交互的沟通成本,提升开发效率。在web中引用会将动画转为Canvas
1,安装插件 npm install svgaplayerweb —save
2,在组件中引用 import SVGA from "svgaplayerweb"
3,使用
<template>
<div id="demoCanvas" ref="demoCanvas"></div>
</template>
<script>
import SVGA from "svgaplayerweb";
export default {
data(){
return{
bgImg:'https://file.nidong.com/upload/gift/20200520/upload_l3xlns9v1in4heomhwgbndzxt8quc9yb.svga'
}
},
mounted() { // SVGA只能在页面渲染好后执行因为需要获取页面中id为‘demoCanvas’的标签
this.setFill();
this.SVGA();
},
methods: {
SVGA() {
let player = new SVGA.Player("#demoCanvas");
let parser = new SVGA.Parser("#demoCanvas");
parser.load(this.bgImg,function(videoItem) { //this.bgImg,图片路径需要线上地址,本地引用会报错
player.setVideoItem(videoItem);
player.startAnimation();
}
);
},
setFill() { //适配不同屏
var $_canvas = document.getElementById("demoCanvas"),
w = window.innerWidth,
h = window.innerHeight,
screen_proportion = h / w,
svga_proportion = 16 / 9;
if (screen_proportion > svga_proportion) {
//长屏幕
$_canvas.style.width = h / svga_proportion + "px";
$_canvas.style.left = (w - h / svga_proportion) / 2 + "px";
} else {
$_canvas.style.height = w * svga_proportion + "px";
$_canvas.style.top = (h - w * svga_proportion) / 2 + "px";
}
}
}
};
</script>
<style lang="scss" scoped>
#demoCanvas { //因需求背景为动态图
position:fixed;
width: 100%;
height: 100%;
top: 0;
left: 0;
z-index: -1;
}
</style>