当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 使用JS和canvas实现gif动图的停止和播放代码

使用JS和canvas实现gif动图的停止和播放代码

2017年12月12日  | 移动技术网IT编程  | 我要评论

html5 canvas可以读取图片信息,绘制当前图片。于是可以实现图片马赛克,模糊,色值过滤等很多图片特效。我们这里不用那么复杂,只要读取我们的图片,重绘下就可以。


html代码:

<img id="testimg" src="xxx.gif" width="224" height="126">
<p><input type="button" id="testbtn" value="停止"></p>

js代码:

if ('getcontext' in document.createelement('canvas')) {
 htmlimageelement.prototype.play = function() {
  if (this.storecanvas) {
   // 移除存储的canvas
   this.storecanvas.parentelement.removechild(this.storecanvas);
   this.storecanvas = null;
   // 透明度还原
   image.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;
   }
  }
 };
}
 
var image = document.getelementbyid("testimg"), 
 button = document.getelementbyid("testbtn");
 
if (image && button) {
 button.onclick = function() {
  if (this.value == '停止') {
   image.stop();
   this.value = '播放';
  } else {
   image.play();
   this.value = '停止';
  }
 };
}

上面代码并未详尽测试,以及可能的体验问题(ie闪动)没有具体处理(影响原理示意),若要实际使用,需要自己再微调完美下。

不足:

1. ie9+支持。ie7/ie8不支持canvas没搞头。

2. 只能停止gif,不能真正意义的暂停。因为canvas获得的gif图片信息为第一帧的信息,后面的貌似获取不到。要想实现暂停,而不是停止,还需要进一步研究,如果你有方法,非常欢迎分享。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网