1. 程式人生 > >SVG中text沿path居中

SVG中text沿path居中

http://stackoverflow.com/questions/15495978/svg-circled-text-on-textpath-center-align

define your text path as the complete upper hemisphere of the elliptical arc you want to draw on:

<pathid="textPath"d="M 250 500 A 250,150 0 1 1 750,500"/>

and set the startOffset of your textPath to 50%. note that your svg file is not well-formed as it is lacking the namespace definition for xlink. the following is a working standalone example:

<?xml version="1.0" encoding="utf-8"?><!-- SO: http://stackoverflow.com/questions/15495978/svg-circled-text-on-textpath-center-align  --><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><svgxmlns="http://www.w3.org/2000/svg"xmlns:xhtml="http://www.w3.org/1999/xhtml"
xmlns:xlink="http://www.w3.org/1999/xlink"version="1.1"width="20cm"height="20cm"viewBox="0 0 1000 1000"preserveAspectRatio="xMinYMin"style="background-color:white;border: solid 1px black;"><defs><pathid="textPath"d="M 250 500 A 250,150 0 1 1 750,500"/></defs><textx="0"y="0"text-anchor="middle"style="font-size
:30pt;"><textPathxlink:href="#textPath"startOffset="50%">here goes my text</textPath></text></svg>
這裡有兩個屬性需要特別注意。

一個是text-anchor,另一個是startOffset。

text-anchor是指一個字元的座標在這個字元中的位置。

下面的例子來自於MDN,很明白易懂。

Example

<?xml version="1.0"?>
<svg width="120" height="120" viewBox="0 0 120 120"
     xmlns="http://www.w3.org/2000/svg" version="1.1">

    <!-- Materialisation of anchors -->
    <path d="M60,15 L60,110 M30,40 L90,40 M30,75 L90,75 M30,110 L90,110" stroke="grey" />
    
    
    <!-- Anchors in action -->
    <text text-anchor="start"
          x="60" y="40">A</text>

    <text text-anchor="middle"
          x="60" y="75">A</text>

    <text text-anchor="end"
          x="60" y="110">A</text>

    <!-- Materialisation of anchors -->
    <circle cx="60" cy="40" r="3" fill="red" />
    <circle cx="60" cy="75" r="3" fill="red" />
    <circle cx="60" cy="110" r="3" fill="red" />

<style><![CDATA[
text{
    font: bold 36px Verdana, Helvetica, Arial, sans-serif;
}
]]></style>
</svg>

Live sample

startOffset是指字元在這個path中的位置,通過百分比表示。