使用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)文章
配置Grunt的Task時通配符支持和動態(tài)生成文件名問題
這篇文章主要介紹了配置Grunt的Task時通配符支持和動態(tài)生成文件名問題,需要的朋友可以參考下2015-09-09js使用棧來實現(xiàn)10進制轉(zhuǎn)8進制與取除數(shù)及余數(shù)
這篇文章主要介紹了js使用棧來實現(xiàn)10進制轉(zhuǎn)8進制、js取除數(shù)、余數(shù),需要的朋友可以參考下2014-06-06如何使用ES6的class類繼承來實現(xiàn)絢麗小球效果
JS是由ES(ECMAScript)、DOM(瀏覽器文檔對象)、BOM(瀏覽器對象模型)組成,這篇文章主要給大家介紹了關(guān)于如何使用ES6的class類繼承來實現(xiàn)絢麗小球效果的相關(guān)資料,需要的朋友可以參考下2021-06-06