共计 1958 个字符,预计需要花费 5 分钟才能阅读完成。
前几天看到 @徐小夕的文章,生成抖音格调的 gif 图,感觉蛮好玩的。于是本人写了一个生成赛博朋克格调 2077 格调的 gif 图生成器。
原理和徐小夕一样,应用 dom-to-image 每距离 16ms 生成一张图片,而后应用 gif.js 将图片合成 gif 图。
生成 gif 图源码如下????
<!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>
最初的成果????
字体应用了赛博朋克的字体,字体抖动款式应用 text-shadow 实现。
全副源码地址:https://github.com/peoplesing…
正文完