如何将包含多个独立GIF/WEBP的DIV导出为单个GIF/WEBP?
实现1000×1000容器铺满小GIF并导出为GIF文件
功能需求
- 页面背景设为灰色,中央展示一个1000×1000像素的白色容器
- 在白色容器内铺满10×10像素的小GIF图
- 添加按钮,点击后将容器内容导出为单个GIF文件
完整实现代码
<!DOCTYPE html> <html> <head> <style> body { background-color: gray; } .container { background-color: white; display: flex; justify-content: center; align-items: center; width: 1000px; height: 1000px; margin: 0 auto; position: relative; } .gif { position: absolute; top: 0; left: 0; width: 10px; height: 10px; margin: 0; padding: 0; } .button-container { display: flex; justify-content: center; margin-top: 20px; } .save-button { padding: 10px 20px; background-color: #4caf50; color: white; border: none; cursor: pointer; } </style> </head> <body> <div class="container"></div> <div class="button-container"> <button class="save-button">Save as GIF</button> </div> <script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/gif.js@0.2.0/dist/gif.min.js"></script> <script> const container = document.querySelector(".container"); const img = new Image(); img.src = "https://gifdb.com/images/high/mlg-dark-souls-video-game-play-z2y2ghg4nj1upfym.webp"; img.onload = function () { const gifWidth = 10; const gifHeight = 10; const containerWidth = container.offsetWidth; const containerHeight = container.offsetHeight; const numCols = Math.ceil(containerWidth / gifWidth); const numRows = Math.ceil(containerHeight / gifHeight); for (let i = 0; i < numRows; i++) { for (let j = 0; j < numCols; j++) { const gif = document.createElement("img"); gif.src = img.src; gif.classList.add("gif"); gif.style.top = i * gifHeight + "px"; gif.style.left = j * gifWidth + "px"; container.appendChild(gif); } } }; const saveButton = document.querySelector(".save-button"); saveButton.addEventListener("click", function () { html2canvas(container).then(function (canvas) { const gif = new GIF({ workers: 2, quality: 10, width: canvas.width, height: canvas.height, }); gif.addFrame(canvas, { delay: 100 }); gif.render(); gif.on("finished", function(blob) { const img = document.createElement("img"); img.src = URL.createObjectURL(blob); document.body.appendChild(img); // 可选:添加下载链接 const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = 'container.gif'; a.click(); }); }); }); </script> </body> </html>
关键实现说明
布局样式:
- 页面body设置灰色背景,白色容器通过
margin: 0 auto居中,使用相对定位为小GIF的绝对定位提供基准 - 小GIF元素设置绝对定位,固定宽高10px,通过循环计算top和left值铺满整个容器
- 页面body设置灰色背景,白色容器通过
动态生成GIF网格:
- 先加载目标GIF图,确保图片加载完成后再计算容器与小GIF的比例
- 通过
Math.ceil计算需要的行数和列数,循环创建并插入小GIF元素,实现铺满效果
导出GIF功能:
- 使用
html2canvas库将容器DOM元素转换为canvas对象 - 借助
GIF.js库,将canvas添加为帧并渲染生成GIF文件 - 渲染完成后创建图片元素展示结果,同时可添加下载链接直接导出文件
- 使用
内容的提问来源于stack exchange,提问作者Kirk Bentish
相关产品推荐
相关产品推荐

