一共有三种方式
GIF+非GIF方式
原理:
播放的时候用gif图片
暂停的时候用非gif图片
缺点
所谓”暂停”的时候,永远是那一张非gif图
css控制
demo
原理
使用css来控制,关键点是animation-play-state: paused;
缺点
本质上是帧动画,不是gif
如果手头上是gif,用这样的方式就要去format格式
canvas
原理
扩展了img标签的方法,可以使用play和stop了
canvas可以读取image,canvas.toDataURL
缺点
stop的时候是gif的第一帧
play的时候是gif的第一帧(除非你让gif肆意播放,因为下面的代码里是替换src属性的)
本质上,canvas方法是第一种方法的进阶,只是canvas可以读取那个非gif图片,不需要你人工的去指定了
if ('getContext' in document.createElement('canvas')) {
HTMLImageElement.prototype.play = function() {
if (this.storeCanvas) {
// 移除存储的canvas
this.storeCanvas.parentElement.removeChild(this.storeCanvas);
this.storeCanvas = null;
// 透明度还原
this.style.opacity = '';
}
if (this.storeUrl) {
this.src = this.storeUrl;
}
};
HTMLImageElement.prototype.stop = function() {
var canvas = document.createElement('canvas');
// 尺寸
var width = this.width,
height = this.height;
if (width & height) {
// 存储之前的地址
if (!this.storeUrl) {
this.storeUrl = this.src;
}
// canvas大小
canvas.width = width;
canvas.height = height;
// 绘制图片帧(第一帧)
canvas.getContext('2d').drawImage(this, 0, 0, width, height);
// 重置当前图片
try {
this.src = canvas.toDataURL("image/gif");
} catch (e) {
// 跨域
this.removeAttribute('src');
// 载入canvas元素
canvas.style.position = 'absolute';
// 前面插入图片
this.parentElement.insertBefore(canvas, this);
// 隐藏原图
this.style.opacity = '0';
// 存储canvas
this.storeCanvas = canvas;
}
}
};
}