在SVG中心对齐对象 [英] Aligning the objects in SVG center

查看:46
本文介绍了在SVG中心对齐对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在svg标签中心内对齐对象.我可以通过调整viewbox中的x,y cordiantes使其对齐.但是每次我需要根据对象的大小更改值.如何在任何大小的对象各自的SVG中实现对象居中.更清楚地说,我希望图标在红色边框内水平和垂直居中.请在下面参考我的代码

How can i align objects within svg tag center. I can make it aligned by adjusting the x,y cordiantes in viewbox. But every time i need to change the value according to the size of object. How can i achieve centering the object within SVG respective of any size of object. To be more clear i want the icon to be centered horizontally and vertically within the red border. Refer my code below

svg{
  border:1px solid red;
}

<svg height="20" width="20" viewBox="0 0 35 35">
	<path fill="#6d6d6d" fill-rule="evenodd" d="M19.0625,8.75 C18.81,8.75 18.585,8.6475 18.415,8.4875 C18.41,8.4825 18.4025,8.4825 18.3975,8.4775 L16.0675,6.145 L10.1675,12.045 C9.5575,12.6525 8.5675,12.6525 7.9575,12.045 C7.3475,11.435 7.3475,10.445 7.9575,9.835 L13.855,3.9375 L11.5225,1.6025 C11.5175,1.5975 11.5175,1.59 11.5125,1.585 C11.3525,1.415 11.25,1.19 11.25,0.9375 C11.25,0.42 11.67,0 12.1875,0 L18.75,0 C19.44,0 20,0.56 20,1.25 L20,7.8125 C20,8.33 19.58,8.75 19.0625,8.75 Z M2.5,5.625 L2.5,16.875 C2.5,17.22 2.78,17.5 3.125,17.5 L14.375,17.5 C14.72,17.5 15,17.22 15,16.875 L15,10 L17.5,12.5 L17.5,17.5 C17.5,18.8825 16.3825,20 15,20 L2.5,20 C1.12,20 0,18.8825 0,17.5 L0,5 C0,3.62 1.12,2.5 2.5,2.5 L7.5,2.5 L10,5 L3.125,5 C2.78,5 2.5,5.28 2.5,5.625 Z"/>
</svg>

推荐答案

您可以使用getBBox()获取路径的大小,然后相应地调整viewBox ...

you can use getBBox() to get the size of your path, and then adjust your viewBox accordingly...

var box=path.getBBox()
svg.setAttribute("viewBox",`${box.x} ${box.y} ${box.width} ${box.height}`)

console.log(box)

svg{border:1px solid red}

<svg id="svg" height="20" width="20" viewBox="0 0 35 35">
	<path id="path" fill="#6d6d6d" fill-rule="evenodd" d="M19.0625,8.75 C18.81,8.75 18.585,8.6475 18.415,8.4875 C18.41,8.4825 18.4025,8.4825 18.3975,8.4775 L16.0675,6.145 L10.1675,12.045 C9.5575,12.6525 8.5675,12.6525 7.9575,12.045 C7.3475,11.435 7.3475,10.445 7.9575,9.835 L13.855,3.9375 L11.5225,1.6025 C11.5175,1.5975 11.5175,1.59 11.5125,1.585 C11.3525,1.415 11.25,1.19 11.25,0.9375 C11.25,0.42 11.67,0 12.1875,0 L18.75,0 C19.44,0 20,0.56 20,1.25 L20,7.8125 C20,8.33 19.58,8.75 19.0625,8.75 Z M2.5,5.625 L2.5,16.875 C2.5,17.22 2.78,17.5 3.125,17.5 L14.375,17.5 C14.72,17.5 15,17.22 15,16.875 L15,10 L17.5,12.5 L17.5,17.5 C17.5,18.8825 16.3825,20 15,20 L2.5,20 C1.12,20 0,18.8825 0,17.5 L0,5 C0,3.62 1.12,2.5 2.5,2.5 L7.5,2.5 L10,5 L3.125,5 C2.78,5 2.5,5.28 2.5,5.625 Z"/>
</svg>

P.S .:只需执行一次,然后在代码中手动更改viewBox ...

P.S.: just do this once and change your viewBox manually in your code...

这篇关于在SVG中心对齐对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆