SVG路径简化美化技术求助:拆解style属性并优化路径坐标
解决SVG Path样式拆解与坐标格式化问题
以下是直接可用的JavaScript代码,可在浏览器控制台或项目脚本中运行,完成你需要的SVG处理:
// 获取目标SVG元素 const svg = document.querySelector('svg'); // 遍历所有path元素 svg.querySelectorAll('path').forEach(path => { // 解析path的style属性 const computedStyle = window.getComputedStyle(path); // 提取并设置独立样式属性 if (computedStyle.transform !== 'none') { path.setAttribute('transform', computedStyle.transform); } path.setAttribute('stroke-width', computedStyle.strokeWidth); path.setAttribute('stroke-linecap', computedStyle.strokeLinecap); path.setAttribute('stroke-linejoin', computedStyle.strokeLinejoin); path.setAttribute('fill', computedStyle.fill); // 固定设置stroke颜色 path.setAttribute('stroke', '#929292'); // 处理d属性,坐标保留两位小数 let d = path.getAttribute('d'); // 正则匹配所有数字(含正负、小数),替换为保留两位小数的格式 d = d.replace(/[-+]?\d+\.?\d*/g, num => { return parseFloat(num).toFixed(2); }); path.setAttribute('d', d); // 移除原style属性 path.removeAttribute('style'); }); // 输出处理后的SVG字符串 console.log(svg.outerHTML);
代码说明
- 样式拆解:通过
getComputedStyle获取path的最终计算样式,确保能正确提取transform、stroke-width等属性值,再逐个设置为path的独立属性。 - 坐标格式化:用正则表达式匹配
d属性里的所有数值,通过toFixed(2)将其格式化为两位小数,保留数值的正负号。 - 固定stroke颜色:强制设置
stroke为#929292,覆盖原有样式。 - 清理冗余:最后移除原有的
style属性,完成样式拆解。
如果你的SVG是字符串形式而非DOM元素,可先将字符串转为DOM再处理:
const svgStr = '<svg>...</svg>'; // 你的SVG字符串 const parser = new DOMParser(); const doc = parser.parseFromString(svgStr, 'image/svg+xml'); const svg = doc.querySelector('svg'); // 后续处理逻辑同上
内容的提问来源于stack exchange,提问作者Theodore John
相关产品推荐
相关产品推荐

