以编程为中心SVG路径 [英] Programmatically centering svg path
问题描述
我正在从一个SVG文件根据访问者的屏幕分辨率生成一个jpg墙纸的PHP脚本。所述壁纸包括一个圆形梯度(矩形)背景和在它上面的路径的。你会如何去水平和垂直居中的矩形路径?请记住,矩形的大小和比例没有一个常数。我应该分开的背景和路径不同的SVG文件或者是有一个简单的方法来中心的路径?也许一个框架?
这是easilly使用嵌套实现< SVG>
元素和 preserveAspectRatio
属性。把你在外面SVG背景和内层一个路径。
< XML版本=1.0编码=UTF-8? >
< SVG的xmlns =http://www.w3.org/2000/svg版本=1.1WIDTH =100%高度=100%>
<矩形的id =背景WIDTH =100%高度=100%补=灰色/>
< SVG preserveAspectRatio =xMidYMid大会的viewBox =0 0 30 40WIDTH =100%高度=100%>
&其中g取代;
<圆CX =15CY =20R =10填补=黄色/>
<圆CX =12CY =17R =1.5补=黑/>
<圆CX =18CY =17R =1.5补=黑/>
<路径D =M 10月23日一8月13日0 0 0 20 23行程=黑笔划宽度=2补=无/>
&所述; / g取代;
< / SVG>
< / SVG>
运行这段代码,并尝试调整窗口大小。
要得到这个工作,你需要确保的是,viewBox属性在内< SVG>
元素的设置是否正确。
I'm working on a PHP script that generates a jpg wallpaper from an SVG-file according to the screen resolution of the visitor. The wallpaper consists of a circular gradient (rectangle) background and a path on top of it. How would you go about centering the path horizontally and vertically to the rectangle? Remember that the rectangle's size and proportions are not a constant. Should I separate the background and path to different svg files or is there an easy way to center paths? Maybe a framework?
This is easilly achieved by using nested <svg>
elements and the preserveAspectRatio
attribute. Put your background in the outer svg and your path in the inner one.
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="100%" height="100%">
<rect id="background" width="100%" height="100%" fill="grey"/>
<svg preserveAspectRatio="xMidYMid meet" viewBox="0 0 30 40" width="100%" height="100%">
<g>
<circle cx="15" cy="20" r="10" fill="yellow"/>
<circle cx="12" cy="17" r="1.5" fill="black"/>
<circle cx="18" cy="17" r="1.5" fill="black"/>
<path d="M 10 23 A 8 13 0 0 0 20 23" stroke="black" stroke-width="2" fill="none"/>
</g>
</svg>
</svg>
Run this snippet and try resizing the window.
To get this to work, all you need to ensure is that the viewBox attribute on the inner <svg>
element is correctly set.
这篇关于以编程为中心SVG路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!