首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >简化svg (删除viewBox属性)以获得纯svg路径

简化svg (删除viewBox属性)以获得纯svg路径
EN

Stack Overflow用户
提问于 2020-08-17 16:28:34
回答 1查看 828关注 0票数 1

我需要用javascript在pdf文件上精确地写一些svgs。我的网页应用程序让用户做出他们的图纸,然后我裁剪这些图纸,以删除未使用的空白,并保存在一个pdf。裁剪svg添加了viewBox属性,大多数可用的js库都不支持这个属性。这意味着位置和规模因素是错误的!因此,我解决这个问题的尝试是简化svg,然后将它放到pdf文件中。据我所知,很少有实用程序可以完成此任务:

  • svgcleaner
  • svgo
  • scour

不幸的是,它们中没有一个完全删除viewbox属性。考虑到这个任务应该是完全自动化的,所以使用inkscape或这样的程序是不可能的解决方案。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-08-18 09:48:11

正如我所评论的:

viewBox属性的值是一个由四个数字组成的列表: min-x、min-y、宽度和高度。如果min=min=0,则可以使用其他2个数字作为svg元素的宽度和高度。然而,当您剪切svg元素时,min-x & min-y不会是0。这意味着您需要将所有内容包装在一个组中,并将组转换为相反的方向:-min&- min-y。

或者,您可以首先将d属性转换为所有相关命令,而不是转换,您可以更改第一个移动到(M)值,从而重新计算路径。

请阅读我的代码中的评论。

代码语言:javascript
复制
// get the viewBox of the original svg element and split it by space or commas
let vb = original.getAttribute("viewBox").split(/[ ,]+/);
//console.log(vb); // ["103", "118", "94", "83"]

//set the width and the height of the copy
copy.setAttribute("width",vb[2]);
copy.setAttribute("height",vb[3]);

// get the d attribute of the original
let path = document.querySelector("#original path").getAttribute("d");

let pathRel = Snap.path.toRelative(path);
//console.log(pathRel)
//change the coords of the first move to command
pathRel[0][1] -= vb[0];
pathRel[0][2] -= vb[1];

//a variable to be used as the d attribute for the copy path
let d = ""  
pathRel.forEach(p=>{d+=(p.join(" "))})
//console.log(d)
//set the d attribute of the copy path
document.querySelector("#copy path").setAttribute("d",d)
代码语言:javascript
复制
#original{width:94px;}
svg{border:solid}
代码语言:javascript
复制
<script src="https://cdn.jsdelivr.net/snap.svg/0.3.0/snap.svg.js"></script>

<svg id="original" viewBox="103 118 94 83"><path d="M144.974,122.645Q150,114,155.026,122.645L194.974,191.355Q200,200,190,200L110,200Q100,200,105.026,191.355Z"></path></svg>


<svg id="copy" ><path></path></svg>

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63454919

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档