我的示例代码是
<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>
多边形点将从服务加载,我想调整多边形并缩放多边形以适应24 x 24区域。
提前致谢
答案 0 :(得分:2)
您需要使用getBBox()
函数中的值,并将viewBox
更新为这些值。
var myPath = document.getElementById("p1")
var mySvg = document.getElementById("s1")
var b = myPath.getBBox();
mySvg.setAttribute("viewBox", [b.x, b.y, 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>
答案 1 :(得分:0)
因为你的观点是动态的。您可以动态计算多边形尺寸以设置视口的高度和宽度
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>