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

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

HTML代码:

<img id="testImg" src="/UploadFiles/2021-04-02/xxx.gif">

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图片信息为第一帧的信息,后面的貌似获取不到。要想实现暂停,而不是停止,还需要进一步研究,如果你有方法,非常欢迎分享。

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

标签:
canvas,gif,动画,canvas,gif,html5,canvas,gif

免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
狼山资源网 Copyright www.pvsay.com

稳了!魔兽国服回归的3条重磅消息!官宣时间再确认!

昨天有一位朋友在大神群里分享,自己亚服账号被封号之后居然弹出了国服的封号信息对话框。

这里面让他访问的是一个国服的战网网址,com.cn和后面的zh都非常明白地表明这就是国服战网。

而他在复制这个网址并且进行登录之后,确实是网易的网址,也就是我们熟悉的停服之后国服发布的暴雪游戏产品运营到期开放退款的说明。这是一件比较奇怪的事情,因为以前都没有出现这样的情况,现在突然提示跳转到国服战网的网址,是不是说明了简体中文客户端已经开始进行更新了呢?