Use JS and canvas to stop and play gif animations.
HTML5 canvas can read image information and draw the current image. Therefore, image mosaic, blur, color value filtering, and many other image effects can be implemented. We don't need to be so complicated here. We only need to read our images and redraw them.
HTML code:
<p> <input type = "button" id = "testBtn" value = "Stop"> </p>
JS Code:
If ('getcontext' in document. createElement ('canvas ') {HTMLImageElement. prototype. play = function () {if (this. storeCanvas) {// remove the stored canvas this. storeCanvas. parentElement. removeChild (this. storeCanvas); this. storeCanvas = null; // restore image transparency. 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) {// store the previous address if (! This. storeUrl) {this. storeUrl = this. src;} // canvas size canvas. width = width; canvas. height = height; // draw the image frame (first frame) canvas. getContext ('2d '). drawImage (this, 0, 0, width, height); // reset the current image try {this. src = canvas. toDataURL ("image/gif");} catch (e) {// cross-origin this. removeAttribute ('src'); // loads the canvas Element canvas. style. position = 'absolute '; // Insert the image above this. parentElement. insertBefore (canvas, this); // hide the source image this. style. opacity = '0'; // stores canvas this. storeCanvas = canvas ;}};}var image = document. getElementById ("testImg"), button = document. getElementById ("testBtn"); if (image & button) {button. onclick = function () {if (this. value = 'stop') {image. stop (); this. value = 'player';} else {image. play (); this. value = 'stop ';}};}
The above Code has not been thoroughly tested, and there is no specific handling (Impact Principle diagram) for possible experience problems (IE flash). If you need to actually use it, you need to fine-tune it.
Disadvantages:
1. IE9 + support. IE7/IE8 does not support canvas headers.
2. You can only stop the gif and cannot pause the gif. Because the GIF image information obtained by the canvas is the information of the first frame, it does not seem to be available later. To pause, rather than stop, you need further research. If you have any methods, please share them with us.
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.