欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

使用JS和canvas實現(xiàn)gif動圖的停止和播放代碼

 更新時間:2017年09月01日 08:57:56   作者:Leon  
這篇文章主要介紹了使用JS和canvas實現(xiàn)gif動圖的停止和播放代碼,非常具有實用價值,需要的朋友可以參考下

HTML5 canvas可以讀取圖片信息,繪制當前圖片。于是可以實現(xiàn)圖片馬賽克,模糊,色值過濾等很多圖片特效。我們這里不用那么復(fù)雜,只要讀取我們的圖片,重繪下就可以。


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閃動)沒有具體處理(影響原理示意),若要實際使用,需要自己再微調(diào)完美下。

不足:

1. IE9+支持。IE7/IE8不支持canvas沒搞頭。

2. 只能停止gif,不能真正意義的暫停。因為canvas獲得的gif圖片信息為第一幀的信息,后面的貌似獲取不到。要想實現(xiàn)暫停,而不是停止,還需要進一步研究,如果你有方法,非常歡迎分享。

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論