以编程方式居中 svg 路径 [英] Programmatically centering svg path

查看:30
本文介绍了以编程方式居中 svg 路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个 PHP 脚本,该脚本根据访问者的屏幕分辨率从 SVG 文件生成 jpg 墙纸.墙纸由圆形渐变(矩形)背景和其顶部的路径组成.您将如何将路径水平和垂直居中到矩形?请记住,矩形的大小和比例不是常数.我应该将背景和路径分开到不同的 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?

推荐答案

这可以通过使用嵌套的 元素和 preserveAspectRatio 属性轻松实现.将您的背景放在外部 svg 中,将您的路径放在内部.

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.

要使其工作,您需要确保正确设置内部 元素上的 viewBox 属性.

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屋!

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