You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在SVG多边形内垂直水平居中放置“Y”图形?

解决方案:通过计算边界框调整transform实现精确居中

步骤1:确定轮廓与Y图形的中心坐标

  • 轮廓(outline)是不规则多边形,通过路径点可算出其边界框:x范围11-89,y范围5-95,中心坐标为 (50, 50)。
  • Y图形(#Y path)自身的边界框中心约为 (54.24, 57.20)(通过路径点坐标计算得出)。

步骤2:调整transform属性

原代码中translate(11,5)会让Y的中心落在SVG坐标系的(65.24, 62.20),偏离了轮廓中心。我们需要将Y的中心平移到(50,50),计算新的偏移量:

  • x方向偏移:50 - 54.24 = -4.24
  • y方向偏移:50 - 57.20 = -7.20

修改#Y的transform属性即可完成居中。

最终SVG代码

<svg id="logo" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" fill="none">
    <title>Loader Logo</title>
    <g>
        <g id="Y" transform="translate(-4.24, -7.20)">
            <path
                  d="m 35,37.018555 c 3.686193,8.066969 7.372385,16.133937 11.058578,24.200905 0,6.557364 0,13.114728 0,19.672093 2.577904,0.07335 5.155807,0.146697 7.733711,0.220046 0,-6.753756 0,-13.507511 0,-20.261265 4.224292,-8.815029 8.450947,-17.628029 12.673514,-26.444539 -2.882118,-0.08201 -5.764235,-0.16401 -8.646353,-0.246014 -2.621719,5.556806 -5.242844,11.114115 -7.86433,16.671119 -2.596764,-5.705351 -5.191816,-11.412041 -7.78969,-17.116521 -2.929616,-0.08336 -5.859232,-0.166714 -8.788847,-0.250069 0.541139,1.184749 1.082278,2.369497 1.623417,3.554245 z"
                  fill="#64ffda"/>
        </g>
        <path id="outline"
            stroke="#64ffda"
            strokeWidth="5"
            strokeLinecap="round"
            strokeLinejoin="round"
            fill="none"
            d="M 50, 5
                  L 11, 27
                  L 11, 72
                  L 50, 95
                  L 89, 73
                  L 89, 28 z"
        />
    </g>
</svg>

动态适配方案(适合复杂场景)

如果需要适配不同尺寸的SVG,可通过JavaScript自动计算边界框并调整偏移:

const outline = document.getElementById('outline');
const yGroup = document.getElementById('Y');
const yPath = yGroup.querySelector('path');

// 获取元素边界框
const outlineBBox = outline.getBBox();
const yBBox = yPath.getBBox();

// 计算中心位置
const outlineCenterX = outlineBBox.x + outlineBBox.width / 2;
const outlineCenterY = outlineBBox.y + outlineBBox.height / 2;
const yCenterX = yBBox.x + yBBox.width / 2;
const yCenterY = yBBox.y + yBBox.height / 2;

// 设置居中偏移
yGroup.setAttribute('transform', `translate(${outlineCenterX - yCenterX}, ${outlineCenterY - yCenterY})`);

这个方法会自动对齐两个元素的中心,确保Y图形始终居中于轮廓内,无需手动计算坐标。

内容的提问来源于stack exchange,提问作者Dorian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 12:34:58