演示站直接放出原站链接:https://demo.demohuo.top/jquery/46/4605/demo/
直接贴出代码:
<!doctype html> <html> <head> <meta charset="utf-8"> <title>模拟GIF动画上传成静态图片并可控制播放与暂停</title> <script src="https://libs.baidu.com/jquery/1.10.2/jquery.min.js"></script> <style> body{padding: 30px} *{margin: 0; padding: 0;} .fileBtn{display: inline-block; position: relative; width: 60px; height: 30px;} .fileBtn label{position: absolute; left: 0; top: 0; width: 100%; height: 100%; background: #108bff; color: #fff; border-radius: 100px; text-align: center; line-height: 30px; font-size: 14px; cursor: pointer;} .fileBtn input{width: 0; height: 0;} .gif{border: solid 1px #ccc; float: left;} </style> </head> <body> <h3>请选择一张gif图片上传查看效果,上传后鼠标移动到图片上gif播放,离开暂停</h3> <div class="fileBtn"> <label for="file">上传</label> <input type="file" id="file" accept="image/*" multiple="multiple"> </div> </body> <script> //dataURLtoBlob("a.gif"); // base64 转 blob function dataURLtoBlob(dataurl) { var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1], bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n); while (n--) { u8arr[n] = bstr.charCodeAt(n); } return new Blob([u8arr], { type: mime }); } // 动态图片转静态 function aniToReview(e){ $(e).each(function () { var canvas = document.createElement('canvas'), ctx = canvas.getContext("2d"), base64 = '', aniUrl = this.src; $(this).one('load', function () { canvas.width = this.width; canvas.height = this.height; ctx.drawImage(this, 0, 0, canvas.width, canvas.height); base64 = canvas.toDataURL("image/png"); var reviewUrl = URL.createObjectURL(dataURLtoBlob(base64)) $(this).attr({ 'src': reviewUrl, 'realsrc': aniUrl }); }); }) } aniToReview('.gif') // 上传文件 $("#file").change(function(file){ var fileList = file.target.files; for(var i=0; i<fileList.length; i++){ if (window.FileReader) { var reader = new FileReader(); reader.readAsDataURL(fileList[i]); reader.onloadend = function (e) { var fileurl = URL.createObjectURL(dataURLtoBlob(e.target.result)); $('body').append('<img class="gif newgif" src='+fileurl+'>') aniToReview('.newgif'); $('.gif').last().removeClass('newgif'); }; } } }); // 鼠标经过时静态图片转动态 $(document).on('mouseover','.gif',function () { var reviewImg = $(this).attr('src'), aniImg = $(this).attr('realsrc'); $(this).attr({'src': aniImg, 'realsrc': reviewImg}); }) $(document).on('mouseout','.gif',function () { var reviewImg = $(this).attr('realsrc'), aniImg = $(this).attr('src'); $(this).attr({'src': reviewImg, 'realsrc': aniImg}); }) </script> </html>
这是一个上传图片临时转换为链接的方法,其实我们可以用这段代码加以修改,可以让我们的网站GIF图片默认是静态的图片,当鼠标经过的时候显示动态的图片,这样可以减少资源的浪费,使得浏览更顺畅。
源代码转自https://www.sucaihuo.com/js/4605.html
声明:本文采用 BY-NC-SA 协议进行授权,如无注明均为原创,转载请注明转自 你好!刘
本文地址:GIF动画上传成静态图片并可鼠标经过播放与暂停
本文地址:GIF动画上传成静态图片并可鼠标经过播放与暂停
发表评论