改变上传的svg颜色并生成新的svg文件,再上传或者更新至服务器上
最近有个需求,就是把上传的svg改颜色,并生成新的svg图片上传值服务器上
<!DOCTYPE html> <html> <head> <title>上传svg并修改颜色得到新的svg文件</title> <style> #svgContainer{ padding: 50px; display: inline-block; } .shake{ animation: shake 1s infinite; } .diffusion{ animation: diffusion 1s infinite; } @keyframes shake { 0% { transform: translateY(0); } 10%,90% { transform: translateY(-2px); } 20%, 80% { transform: translateY(-4px); } 30%,70% { transform: translateY(-6px); } 40%,60% { transform: translateY(-8px); } 50% { transform: translateY(-10px); } 100% { transform: translateY(0); } } @keyframes diffusion { 0% { transform: scale(1)} 10%,90% { transform: scale(1.1); } 20%, 80% { transform: scale(1.2); } 30%, 70% { transform: scale(1.3); } 40%,60% { transform: scale(1.4); } 50% { transform: scale(1.5); } 100% { transform: scale(1); } } </style> </head> <body> <input type="file" id="svgUpload" accept=".svg"> <button id="uploadButton">随机颜色</button> <button id="beatBtn" onclick="changeClassFn('shake')">跳动</button> <button id="diffusionBtn" onclick="changeClassFn('diffusion')">扩散</button> <br /> <div id="svgContainer"></div> <!-- 用于显示 SVG --> </body> <script src="./index.js"></script> </html>
index.js中的代码如下:
const getRandomHexColor = () => { // 生成随机颜色 let letters = '0123456789ABCDEF'; let color = '#'; for (var i = 0; i < 6; i++) { color += letters[Math.floor(Math.random() * 16)]; } return color; } document.getElementById('svgUpload').addEventListener('change', (ev) => { let file = ev.target.files[0]; if (file) { console.log(file, '上传成功的文件') let reader = new FileReader(); reader.onload = (e) => { document.getElementById('svgContainer').innerHTML = e.target.result; } reader.readAsText(file); } }) document.getElementById('uploadButton').addEventListener('click', () =>{ changeClassFn('') let fileInput = document.getElementById('svgUpload'); let file = fileInput.files[0]; if (file) { let reader = new FileReader(); reader.onload = (e) => { document.getElementById('svgContainer').innerHTML = e.target.result; // 在这里可以添加修改 SVG 颜色的代码 changeSvgColor(getRandomHexColor()); }; console.log(file, '修改后的svg文件') reader.readAsText(file);
// 上传新的文件至服务器 uploadFile(file); } }); const uploadFile = (file) => { let formData = new FormData(); formData.append('file', file); console.log(formData) fetch('上传图片地址', { method: 'POST', body: formData, }).then((response) => response.json()).then((result) => { console.log("Success:", result); }) } const changeSvgColor = (color) => { let svg = document.getElementById('svgContainer').querySelector('svg'); if (svg) { // 修改 SVG 所有路径的填充颜色 svg.querySelectorAll('path').forEach((path) => { path.style.fill = color; }); } } const changeClassFn = (className) => { document.getElementById('svgContainer').className = className; }