前幾天看到@徐小夕的文章,生成抖音風格的gif圖,以爲蠻好玩的。因而本身寫了一個生成賽博朋克風格2077風格的gif圖生成器。css
原理和徐小夕同樣,使用dom-to-image每間隔16ms生成一張圖片,而後使用gif.js將圖片合成gif圖。html
生成gif圖源碼以下👇git
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Cyberpunk</title> <link rel="stylesheet" href="./index.css" /> <script src="gif.js"></script> <script src="gif.worker.js"></script> <script src="dom-to-image.min.js"></script> </head> <body> <div id="root"> <div id="content"> <h1 id="title">Cyberpunk</h1> <div id="picture-tube"></div> </div> <button id="export-gif"> 導出gif(多等一會, 若是Chrome提示攔截窗口,請容許彈出窗口) </button> <input id="form" /> <button id="change">修改</button> </div> <div id="warehouse"></div> <script> const warehouse = document.getElementById('warehouse'); const content = document.getElementById('content'); const exportGif = document.getElementById('export-gif'); const form = document.getElementById('form'); const change = document.getElementById('change'); const title = document.getElementById('title'); const createImgs = async function () { warehouse.innerHTML = ''; const tasks = []; for (let i = 1; i < 60; i++) { tasks.push(new Promise((resolve, reject) => { setTimeout(() => { domtoimage.toPng(content).then((url) => { const img = new Image(); img.src = url; img.style.display = 'none'; warehouse.appendChild(img); resolve(img); }).catch((error) => { reject(error) }) }, i * 16); })) } return Promise.all(tasks); } const createGif = async function () { const imgs = warehouse.getElementsByTagName('img'); const gif = new GIF({ workers: 4, quality: 5, width: 580, height: 200, background: '#fff' }); for (let i = 0; i < imgs.length; i++) { gif.addFrame(imgs[i], {delay: 16}); } gif.on('finished', function(blob) { window.open(URL.createObjectURL(blob)); }); gif.render(); } const gif = async () => { await createImgs(); await createGif(); } exportGif.addEventListener('click', gif); change.addEventListener('click', function () { title.innerHTML = form.value; }) </script> </body> </html>
最後的效果👇github
字體使用了賽博朋克的字體,字體抖動樣式使用text-shadow實現。app
所有源碼地址:https://github.com/peoplesing...dom