UI给了一段完整的动效文件,其中有需要用户介入操作才开始播放的,所以采用分段播放,并增加一个div元素定位到svga动画上的按钮位置,并添加点击事件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport"
content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>Demo</title>
</head>
<body>
<div class="first_screen">
<canvas id="canvas"></canvas>
<div id="svga_btn" style="width: 120px;height:120px;position: absolute;top: 44%;left: 0;right:0;margin: auto;">
</div>
</div>
</body>
<script src="/static/js/svga.min.js"></script>
<script type="text/javascript">
var first_screen = document.querySelector('.first_screen');
var canvas = document.getElementById('canvas')
var svga_btn = document.getElementById('svga_btn')
var step = 0;
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
if (sessionStorage.getItem('cxm_paying') == 'true') {
first_screen.remove()
} else {
var parser = new SVGA.Parser('#canvas');
var player = new SVGA.Player('#canvas');
player.setContentMode('AspectFill')
parser.load('https://mdhw.oss-cn-hangzhou.aliyuncs.com/promotion/chou.svga', svga => {
player.setVideoItem(svga)
palyFrame(step);
svga_btn.addEventListener('click', function () {
step++;
palyFrame(step);
svga_btn.style.display = 'none';
})
player.onFinished(function () {
svga_btn.style.display = 'block';
player.clear();
if (step === 2) {
first_screen.remove()
} else {
palyFrame(0)
}
})
})
}
function palyFrame(step) {
switch (step) {
case 0:
player.loops = 0;
player.startAnimationWithRange({ location: 0, length: 120 });
break;
case 1:
// 第一次播放动画
player.loops = 1;
player.startAnimationWithRange({ location: 120, length: 100 });
break;
case 2:
// 第二次播放动画
player.loops = 1;
player.startAnimationWithRange({ location: 340, length: 150 });
break;
default:
return;
}
}
</script>
</html>