[英]How to scale a svg polygon dynamically to fit into 24X 24 size?
My sample code is 我的示例代码是
<svg width="24" height="24" viewBox="0 0 24 24" preserveAspectRatio="xMinYMin"
xmlns="http://www.w3.org/2000/svg">
<polygon points="150,75 258,137.5 258,262.5 150,325 42,262.6 42,137.5"/>
</svg>
the polygon points will be loaded from service and i want to resize and scale the polygon to fit into 24 x 24 area. 多边形点将从服务中加载,我要调整多边形的大小和比例以适合24 x 24区域。
Thanks in advance 提前致谢
You need to use the values from the getBBox()
function and update your viewBox
with those. 您需要使用getBBox()
函数中的值,并使用这些值更新viewBox
。
var myPath = document.getElementById("p1") var mySvg = document.getElementById("s1") var b = myPath.getBBox(); mySvg.setAttribute("viewBox", [bx, by, b.width, b.height].join(" "));
<svg width="24" height="24" id="s1"> <polygon id="p1" points="150,75 258,137.5 258,262.5 150,325 42,262.6 42,137.5"/> </svg>
As your points are dynamic. 由于您的观点是动态的。 You can dynamically calculate the polygon dimension to set the height and width of viewport 您可以动态计算多边形尺寸以设置视口的高度和宽度
var myPath = document.getElementById("p1") var w = myPath.getBoundingClientRect().width; var h = myPath.getBoundingClientRect().height; document.getElementById("s1").setAttribute("viewBox", "0 0 " + h + " " + w);
<svg width="24" height="24" id="s1" xmlns="http://www.w3.org/2000/svg"> <polygon id="p1" points="150,75 258,137.5 258,262.5 150,325 42,262.6 42,137.5"/> </svg>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.