如何在不修改坐标与字号的前提下实现SVG圆内文本居中?
SVG圆形内文本居中解决方案
问题出在字体的内置字形度量:Verdana这类字体的"X"字符,实际视觉范围并没有完全填满font-size定义的高度;再加上dominant-baseline="middle"是基于字体的em框基线系统对齐,而非字符的视觉中心,导致视觉上偏离圆心。
以下是不修改x/y坐标或font-size的解决办法:
方案1:微调垂直对齐参数
保留text-anchor="middle"实现水平居中,将dominant-baseline替换为central(基于视觉中心对齐),再通过dy做细微垂直偏移(不同字体偏移量可能略有不同):
<svg width="200px" height="200px"> <circle r="50" cx="100" cy="100"></circle> <text x="100" y="100" fill="white" font-size="100" text-anchor="middle" dominant-baseline="central" dy="0.05em" font-family="Verdana">X</text> <line x1="50" y1="100" x2="150" y2="100" stroke="red" stroke-width="2"></line> <line x1="100" y1="50" x2="100" y2="150" stroke="red" stroke-width="2"></line> </svg>
方案2:强制文本匹配圆的尺寸
使用textLength指定文本宽度为圆的直径(100px),配合lengthAdjust="spacingAndGlyphs"让字符撑满宽度,同时保持对齐:
<svg width="200px" height="200px"> <circle r="50" cx="100" cy="100"></circle> <text x="100" y="100" fill="white" font-size="100" text-anchor="middle" dominant-baseline="middle" textLength="100" lengthAdjust="spacingAndGlyphs" font-family="Verdana">X</text> <line x1="50" y1="100" x2="150" y2="100" stroke="red" stroke-width="2"></line> <line x1="100" y1="50" x2="100" y2="150" stroke="red" stroke-width="2"></line> </svg>
方案3:改用视觉对齐更准确的字体
如果允许更换字体(仅调整字体类型,不修改大小),Arial Black或monospace这类字体的字符更接近方形,dominant-baseline="middle"就能直接实现完美居中:
<svg width="200px" height="200px"> <circle r="50" cx="100" cy="100"></circle> <text x="100" y="100" fill="white" font-size="100" text-anchor="middle" dominant-baseline="middle" font-family="Arial Black">X</text> <line x1="50" y1="100" x2="150" y2="100" stroke="red" stroke-width="2"></line> <line x1="100" y1="50" x2="100" y2="150" stroke="red" stroke-width="2"></line> </svg>
原理说明
text-anchor="middle":确保文本在水平方向上以x坐标为中心对齐。dominant-baseline="central":相对于字符的视觉中心做垂直对齐,比middle更适配非方形字体。textLength+lengthAdjust:强制文本宽度匹配圆的直径,让字符视觉上填满圆形空间,消除字体自带的边距影响。
内容的提问来源于stack exchange,提问作者rikard
相关产品推荐
相关产品推荐

