如何为SVG边框各边中心设置带transform rotate的文本?
在SVG边框四边中心添加旋转文本的解决方案
核心原理
SVG的transform="rotate(角度, 旋转中心X, 旋转中心Y)"是实现精准对齐的关键:
- 第一个值为旋转角度(逆时针为负,顺时针为正)
- 后两个值是旋转中心点的坐标,必须对应边框边的中心位置,才能让文本旋转后精准贴合边框。
结合你的SVG viewBox(0 0 694 426)和边框路径数据,先明确四边中心坐标:
- 顶部边框中心:
(347, 26.86)(宽度一半为694/2=347,顶部边框Y值从路径提取为26.86) - 底部边框中心:
(347, 399.36)(宽度一半,底部边框Y值从路径提取为399.36) - 左侧边框中心:
(34.79, 213)(左侧边框X值为34.79,高度一半为426/2=213) - 右侧边框中心:
(659.79, 213)(右侧边框X值为659.79,高度一半)
完整代码实现
CSS样式
#text-group > text { fill: white; text-anchor: middle; dominant-baseline: middle; /* 确保文本垂直方向完全居中 */ font-size: 20px; }
SVG代码(整合边框与文本)
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" fill="none" width="100%" height="100%" viewBox="0 0 694 426"> <!-- 原有边框路径 --> <g> <path d="M659.89 4.56006L34.89 4.66006V4.56006H5.48999V421.66H689.29V4.56006H659.89ZM34.89 399.56V26.7601H659.89V399.46L34.89 399.56Z" fill="#34428B"></path> <path d="M343.09 20.06L343.99 20.86L347.49 17.36L350.99 20.86L351.89 20.06L348.39 16.56L351.89 13.06L350.99 12.16L347.49 15.66L343.99 12.16L343.09 13.06L346.59 16.56L343.09 20.06Z" fill="#000010"></path> <path d="M34.79 4.56006V49.1601" stroke="#272425" stroke-width="1.24" stroke-miterlimit="9.62"></path> <path d="M242.69 4.56006V49.1601" stroke="#272425" stroke-width="1.24" stroke-miterlimit="9.62"></path> <path d="M451.89 4.56006V49.1601" stroke="#272425" stroke-width="1.24" stroke-miterlimit="9.62"></path> <path d="M659.79 4.56006V49.1601" stroke="#272425" stroke-width="1.24" stroke-miterlimit="9.62"></path> <path d="M659.79 26.86H34.79V399.36H659.79V26.86Z" stroke="#000008" stroke-width="1.24" stroke-miterlimit="9.62"></path> </g> <!-- 文本组 --> <g id='text-group'> <!-- 顶部文本:逆时针旋转90度,以顶部中心为旋转点 --> <text x="347" y="26.86" transform="rotate(-90 347 26.86)">TOP</text> <!-- 底部文本:逆时针旋转90度,以底部中心为旋转点 --> <text x="347" y="399.36" transform="rotate(-90 347 399.36)">BOTTOM</text> <!-- 左侧文本:逆时针旋转90度,以左侧中心为旋转点 --> <text x="34.79" y="213" transform="rotate(-90 34.79 213)">LEFT</text> <!-- 右侧文本:顺时针旋转90度,以右侧中心为旋转点 --> <text x="659.79" y="213" transform="rotate(90 659.79 213)">RIGHT</text> </g> </svg>
参数说明
- 顶部/底部文本用
rotate(-90):逆时针旋转90度后,文本垂直排列在边框中心,贴合顶部/底部边框走向。 - 左侧文本用
rotate(-90):旋转后文本水平向左排列,贴合左侧边框。 - 右侧文本用
rotate(90):顺时针旋转90度后,文本水平向右排列,贴合右侧边框。 text-anchor: middle和dominant-baseline: middle确保文本在旋转中心点完全居中,避免偏移。
内容的提问来源于stack exchange,提问作者s.kuznetsov
相关产品推荐
相关产品推荐

