我需要用javascript在pdf文件上精确地写一些svgs。我的网页应用程序让用户做出他们的图纸,然后我裁剪这些图纸,以删除未使用的空白,并保存在一个pdf。裁剪svg添加了viewBox属性,大多数可用的js库都不支持这个属性。这意味着位置和规模因素是错误的!因此,我解决这个问题的尝试是简化svg,然后将它放到pdf文件中。据我所知,很少有实用程序可以完成此任务:
不幸的是,它们中没有一个完全删除viewbox属性。考虑到这个任务应该是完全自动化的,所以使用inkscape或这样的程序是不可能的解决方案。
发布于 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)值,从而重新计算路径。
请阅读我的代码中的评论。
// 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)#original{width:94px;}
svg{border:solid}<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>
https://stackoverflow.com/questions/63454919
复制相似问题