本文主要是介绍图片生成box-shadow并下载,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
把图片生成由box-shadow拼接成的阴影组成的图片
html
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>图片生成阴影html</title></head><body><input id="file" type="file" /><button id="btn">制作</button><script src="./index.js"></script></body>
</html>
js
(function () {// 获取元素const files = document.getElementById('file');const btn = document.getElementById('btn');// 添加事件btn.addEventListener('click', () => {const file = files.files[0];if (!file) {alert('请选择图片');return;}// 创建 FileReader 对象 获取文件信息const reader = new FileReader();reader.readAsDataURL(file);reader.onload = function (e) {// 创建 img 元素const img = document.createElement('img');img.src = e.target.result;// img 加载完成img.onload = function () {// 创建 canvas 元素const canvas = document.createElement('canvas');const ctx = canvas.getContext('2d');// 设置 canvas 宽高canvas.width = img.width;canvas.height = img.height;// 将图片绘制到 canvas 上ctx.drawImage(img, 0, 0);// 获取图片的像素数据const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);// 获取图片的 box-shadow 值const boxShadow = getBoxShadows(imageData);// 生成html文件的字符串const html = montageHtml(boxShadow);// 生成html文件downloadHtml(html);};};});// 获取图片的 box-shadow 值function getBoxShadows(imageData) {let boxShadow = '';// 遍历像素数据 获取每个像素的 RGBA 值 X Y 坐标for (let i = 0; i < imageData.data.length; i += 4) {const r = imageData.data[i];const g = imageData.data[i + 1];const b = imageData.data[i + 2];const a = imageData.data[i + 3];const x = (i / 4) % canvas.width;const y = Math.floor(i / 4 / canvas.width);// 拼接box shadowif (boxShadow) {boxShadow += `,${x}px ${y}px 1px rgba(${r}, ${g}, ${b})`;} else {boxShadow += `${x}px ${y}px 1px rgba(${r}, ${g}, ${b})`;}}return boxShadow;}// 生成html文件 并下载function downloadHtml(html) {const blob = new Blob([html], { type: 'text/html' });const url = URL.createObjectURL(blob);const a = document.createElement('a');a.href = url;a.download = 'box-shadow.html';a.click();URL.revokeObjectURL(url);}function montageHtml(boxShadow) {const html = `<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><style>div {width: 1px;height: 1px;box-shadow: ${boxShadow};}</style></head><body><div></div></body></html>`;return html;}
})();
这篇关于图片生成box-shadow并下载的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!