js实现gif
使用 Canvas 和 gif.js 生成 GIF
安装 gif.js 库:
npm install gif.js
基础实现代码:
const GIF = require('gif.js');
// 创建 GIF 实例
const gif = new GIF({
workers: 2,
quality: 10,
width: 200,
height: 200
});
// 添加帧(通过 Canvas)
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
canvas.width = 200;
canvas.height = 200;
// 绘制第一帧
ctx.fillStyle = 'red';
ctx.fillRect(0, 0, 200, 200);
gif.addFrame(canvas, {delay: 100});
// 绘制第二帧
ctx.fillStyle = 'blue';
ctx.fillRect(0, 0, 200, 200);
gif.addFrame(canvas, {delay: 100});
// 渲染 GIF
gif.on('finished', function(blob) {
const img = document.createElement('img');
img.src = URL.createObjectURL(blob);
document.body.appendChild(img);
});
gif.render();
使用 CCapture.js 录制动画为 GIF
安装 CCapture.js:
npm install ccapture.js
实现代码示例:
const CCapture = require('ccapture.js');
const capturer = new CCapture({
format: 'gif',
workersPath: 'node_modules/ccapture.js/build/',
framerate: 60,
quality: 90
});
function startRecording() {
capturer.start();
}
function captureFrame() {
capturer.capture(document.getElementById('canvas'));
}
function stopRecording() {
capturer.stop();
capturer.save();
}
纯前端实现简单 GIF 编码
对于简单需求可以手动实现 GIF 编码:
function createSimpleGIF(frames, width, height) {
// GIF 头部
let gif = 'GIF89a';
// 逻辑屏幕描述符
gif += String.fromCharCode(
width & 0xff, (width >> 8) & 0xff,
height & 0xff, (height >> 8) & 0xff,
0xF0, 0, 0
);
// 全局颜色表(简单黑白)
gif += '\x00\x00\x00\xFF\xFF\xFF';
// 动画控制扩展
gif += '!\xFF\x0BNETSCAPE2.0\x03\x01\x00\x00\x00';
// 添加各帧
frames.forEach(frame => {
// 图像描述符
gif += ',';
gif += String.fromCharCode(
0, 0, 0, 0,
width & 0xff, (width >> 8) & 0xff,
height & 0xff, (height >> 8) & 0xff,
0
);
// 图像数据
gif += '\x08' + frame.pixels;
});
// 结束符
gif += ';';
return gif;
}
性能优化建议
减少 GIF 尺寸可显著提升性能:
- 限制颜色数量(通常 256 色足够)
- 降低帧率(10-15fps 适用于大多数场景)
- 减小画布尺寸
对于复杂动画,考虑使用 Web Worker 进行编码:
const worker = new Worker('gif.worker.js');
worker.postMessage({
frames: capturedFrames,
options: { width: 400, height: 400 }
});
worker.onmessage = function(e) {
const gifBlob = e.data;
// 处理生成的 GIF
};
浏览器兼容性注意事项
现代浏览器基本支持 GIF 生成方案,但需注意:

- IE11 需要 polyfill
- Safari 对某些库可能需要额外配置
- 移动设备应考虑内存限制
以上方案可根据具体需求选择,gif.js 适合大多数场景,CCapture.js 适合录制复杂动画,手动编码则适合极简需求。






