javascript制作gif动图----gif.js
程序员文章站
2024-01-16 21:54:16
...
Javascript制作gif动图
gif.js 官网
软件简介 出自开源软件
gif.js 是一个可直接在浏览器上运行的 JavaScript GIF 编码器。支持的浏览器包括:Google Chrome
Firefox 17
Safari 6
Internet Explorer 10
Mobile Safari iOS 6
使用方法:
var gif = new GIF({
workers: 2,
quality: 10
});
// add an image element
gif.addFrame(imageElement);
// or a canvas element
gif.addFrame(canvasElement, {delay: 200});
// or copy the pixels from a canvas context
gif.addFrame(ctx, {copy: true});
gif.on('finished', function(blob) {
window.open(URL.createObjectURL(blob));
});
gif.render();
JS生成gif并导出base64格式代码
let gifimg1 = document.getElementById('gif1')
let gifimg2 = document.getElementById('gif2')
let gifimg3 = document.getElementById('gif3')
let arr = [gifimg1, gifimg2, gifimg3]
function shezhitupian() {
return new Promise((resolve, reject) => {
let gif = new GIF({
workers: 2,
quality: 10,
width: 100,
height: 100,
// background: '#ffffff',//原透明色替换为白色
// transparent: 0xffffff//把图片中的白色替换为gif的透明色
});
arr.forEach((item, index) => {
console.log(item, index)
let canvas = document.createElement('canvas');
canvas.width = 100
canvas.height = 100
let ctx = canvas.getContext('2d');
ctx.drawImage(item, 0, 0, 96, 96);
ctx.font = "bold 20px Arial";
ctx.fillStyle = "red";
ctx.fillText("test", 64, 64);
gif.addFrame(canvas, { delay: 600 });
if (index == arr.length - 1) {
//渲染图片
gif.render();
}
})
//合成图片成功后
gif.on('finished', function (blob) {
// console.log(URL.createObjectURL(blob))
blobToBase64(blob).then(res => {
resolve({ path: res })
})
window.open(URL.createObjectURL(blob));
});
})
}
function blobToBase64(blob) {
return new Promise((resolve, reject) => {
const fileReader = new FileReader();
fileReader.onload = (e) => {
resolve(e.target.result);
};
fileReader.readAsDataURL(blob);
fileReader.onerror = () => {
reject(new Error('blobToBase64 error'));
};
});
}
上一篇: vtysh的移植