时间:2020-10-07 14:26:04 | 栏目:JavaScript代码 | 点击:次
无意中看到一篇文章写得是关于纯前端处理GIF图片的问题,感觉挺有意思的所以自己也实现了一下;
主要用到的有两个第三方库:合成GIF图片的gif.js和分解的libgif.js;
分解GIF
1. 引入Git库
import SuperGif from './libgif.js'
2. 处理图片
var file = e.target.files[0]; console.log(file.type.indexOf('image/gif')); load_gif(file); function load_gif(gif_source) { var gifImg = document.getElementById('gifImg'); // gif库需要img标签配置下面两个属性 gifImg.setAttribute('rel:animated_src', URL.createObjectURL(gif_source)) gifImg.setAttribute('rel:auto_play', '0') // 新建gif实例 var rub = new SuperGif({ gif: gifImg } ); var running = false; rub.load(function(){ var img_list = []; var j = 0; console.log(rub.get_length()); for (var i=1; i <= rub.get_length(); i++) { // 遍历gif实例的每一帧 rub.move_to(i); var imgImage = new Image(); //canvas生成base64图片数据 imgImage.src = rub.get_canvas().toDataURL('image/jpeg',0.8); } }
合成GIF图片
1. 引入Git库
import GIF from './gif.js'
2. 图片合成
var gif = new GIF({ workers: 2, quality: 10, workerScript: 'js/gif.worker.js' }); var j = 0; var canvas= document.createElement("canvas"); var ctx = tCanvas.getContext('2d'); for (var i=1; i <= len; i++) { var imgImage = new Image(); imgImage.src = img; imgImage.onload = function (e) { //Canvas绘制图片 canvas.width = width; canvas.height = height; console.log(width,height) //铺底色 ctx.fillStyle = "#fff"; ctx.fillRect(0, 0, canvas.width, canvas.height); ctx.drawImage(imgImage, 0, 0, width, height); gif.addFrame(canvas,{copy:true,delay:50}); j++; //图片 if(j>=len) { gif.render() }; } } gif.on('finished', function(blob) { //生成图片链接 var url = URL.createObjectURL(blob); }