1、用animation实现动画
<template>
<div id="animatedGif" class="gif-animation"></div>
</template>
<script>
const animatedDiv = document.getElementById('animatedGif');
// 监听CSS动画的结束事件
animatedDiv.addEventListener('animationend', () => {
console.log('CSS动画结束,相当于GIF播放完成。');
animatedDiv.style.display = 'none'; // 或执行其他操作
});
</script>
<style>
.gif-animation {
width: 200px;
height: 200px;
/* 将动画设置为只播放一次 */
animation: play-gif 2s steps(1) 1 forwards;
}
@keyframes play-gif {
0% { background-image: url('frame1.png'); }
20% { background-image: url('frame2.png'); }
40% { background-image: url('frame3.png'); }
60% { background-image: url('frame4.png'); }
80% { background-image: url('frame5.png'); }
100% { background-image: url('frame6.png'); }
}
</style>
2、用gifler控制gif动画
<template>
<canvas id="gifCanvas" width="113" height="95"></canvas>
</template>
<script>
require('./gifler.min.js');
const canvas = document.getElementById('gifCanvas');
const img = require('@/assets/paopao.gif');
const ins = window.gifler(img);
ins.frames(canvas, function (ctx, frame, i) {
const ratioHeight = canvas.height / this.height;
const ratioWidth = canvas.width / this.width;
const ratio = Math.min(ratioHeight, ratioWidth); // 缩放比例
console.log('11111', this, frame, i, ratio);
ctx.drawImage(frame.buffer, frame.x * ratio, frame.y * ratio, frame.width * ratio, frame.height * ratio);
if (i + 1 === this._frames.length) {
this._running = false; // 只执行一遍
}
}, false); // false避免canvas大小被修改为gif图大小
</script>