最近,项目上又提出了新的需求,要求能够上传三张图片制作为gif图,在网上罗列搜寻了一下,发现目前最主要的方法有两种,一是gif.js,一是gifshot.js。经过功能对比,最终选择了gifshot.js。因为这种方法不仅支持图片转为gif,还支持视频和摄像头制作gif。下面说说如何使用gifshot.js
我们先去gifshot.js的官网了解一下它。
在官网中可以看到,最主要的文件是dist目录下的gifshot.js,官网直接在html文件中引入
<script src='gifshot.js'></script>
然后在js中写
gifshot.createGIF({}, function(obj) {
if(!obj.error) {
var image = obj.image,
animatedImage = document.createElement('img');
animatedImage.src = image;
document.body.appendChild(animatedImage);
}
});
这里默认的是调用摄像头制作gif
gifshot的API相关方法去官网了解,这里不做过多赘述。。。
下面开始创建demo
创建demo的时候,建议创建react或者vue这样的demo,不然访问本地 文件的时候会出现跨域问题,然后又得去解决跨域。。。后面说一下如何解决访问本地文件出现跨域,我这里创建的是react demo。
我们创建好react demo后,将gitshot.js文件放到静态资源目录(static)下,
然后在一个js文件中引入gifshot.js
import React from 'react';
import gifshot from './static/gifshot';
import src1 from './images/1.png'
import src2 from './images/2.png'
import src3 from './images/3.png'
import src4 from './images/4.png'
import src5 from './images/5.png'
import src6 from './images/6.png'
import src7 from './images/7.png'
import src8 from './images/8.png'
function App() {
gifshot.createGIF({
gifWidth: 200,
gifHeight: 200,
// images: [
// 'https://t9.baidu.com/it/u=3363001160,1163944807&fm=79&app=86&size=h300&n=0&g=4n&f=jpeg?sec=1586855265&t=bda8700df538f6be8b0158c0a7f8f7df',
// 'https://t9.baidu.com/it/u=583874135,70653437&fm=79&app=86&size=h300&n=0&g=4n&f=jpeg?sec=1586855265&t=6afcc905d3890e2e10910155fb7c73ed',
// ],
images: [src1, src2, src3, src4, src5, src6, src7, src8],
interval: 0.1,
numFrames: 10,
frameDuration: 1,
fontWeight: 'normal',
fontSize: '16px',
fontFamily: 'sans-serif',
fontColor: '#ffffff',
textAlign: 'center',
textBaseline: 'bottom',
sampleInterval: 10,
numWorkers: 2
}, function (obj) {
if (!obj.error) {
var image = obj.image,
animatedImage = document.createElement('img');
animatedImage.src = image;
document.body.appendChild(animatedImage);
}
});
return (
<div className="App">
</div>
);
}
export default App;
要更改一下gifshot.js的这个地方
// Universal Module Definition (UMD) to support AMD, CommonJS/Node.js, and plain browser loading
if (typeof define === 'function' && define.amd) {
define([], function () {
return API;
});
} else if (typeof exports !== 'undefined') {
module.exports = API;
} else {
window.gifshot = API;
}
不然会提示define is undefined的错误,
我的处理是直接删除了第一个if语句,,,嘿嘿嘿