一、基於SVG文檔的文字居中
text-anchor: middle; //水平方向居中
dominant-baseline: middle; //垂直居中
1.使用內聯樣式配置居中
<svg style=' border:1px solid blue;width:300px;height:300px;'> <path d='M0,150 300,150 M150,0 L150,300 ' fill='none' stroke='green'/> <text fill='red' x='150' y='150' style='dominant-baseline:middle;text-anchor:middle;'> 中文內容,中文內容 </text> </svg>
2.css中配置居中
svg { width: 300px; height: 150px; border:1px solid red; } path { fill: #4682B4; } text { stroke: #fff; stroke-width: 1; font-size: 20px; text-anchor: middle; /* 文本水平居中 */ dominant-baseline: middle; /* 文本垂直居中 */ }
svg代碼:
<svg> <path d="M150 0 L75 200 L225 200 Z" /> <text x='150' y='75'>1233</text> </svg>
二、在TextPath中設置居中
1.定義直線path居中處理
<svg style=' border:1px solid blue;'> <defs> <!-- 相對group 高度是容器的一半,寬度和容器相同 --> <path id="center" d="M0 20,200,20" style="stroke: white; fill: none;" /> </defs> <g transform='translate(50,50)'> <rect width='200' height='40' fill='blue' /> <text style="font-size: 15;stroke:red;text-anchor:middle;dominant-baseline:middle"> <textPath xlink:href="#center" startOffset="50%"> 中文測試內容 </textPath> </text> </g> </svg>
2.定義曲線path,居中處理
<svg style='stroke:green; border:1px solid blue;' > <defs> <path id="short-corner" transform="translate(40,40)" d="M0 0 L 30 0 A 30 30 0 0 1 60 30 L 60 60" style="stroke: gray; fill: none;" /> <path id="long-corner" transform="translate(140,40)" d="M0 0 L 50 0 A 30 30 0 0 1 80 30 L 80 80" style="stroke: gray; fill: none;" /> </defs> <use xlink:href="#short-corner" /> <text style="font-size: 14;"> <textPath xlink:href="#short-corner"> This text is </textPath> </text> <use xlink:href="#long-corner" /> <text style="font-size: 14; text-anchor: middle;"> <textPath xlink:href="#long-corner" startOffset="50%"> centered </textPath> </text> </svg>
3.使用SVG.js 設置居中處理
var draw = SVG('container').size(300, 300); draw.style({ border: '1px solid red' }); var group = draw.group(); var rect = draw.rect(100, 60).fill('green'); group.add(rect); var text = draw.text('測試按鈕'); text.style({ fill: 'red', }); text.path('M0,10 100,10').attr({ fill:'none' }); text.textPath().attr({ startOffset: '50%', 'text-anchor':'middle', 'dominant-baseline':'middle' }); group.add(text); group.move(150, 100); group.on('mouseenter', function () { rect.fill('blue'); }).on('mouseleave', function () { rect.fill('green'); });
相關文章:http://www.php.cn/html5-tutorial-35158.html http://www.cnblogs.com/lovesong/p/5998650.html http://blog.csdn.net/lcy132100/article/details/9722543
更多: