如何在SVG中居中90º旋转文本

时间:2012-08-27 19:32:17

标签: svg d3.js

使用D3时,我希望Y轴标签旋转-90º并以Y轴为中心。我认为这将是一块蛋糕,并写了以下内容:

// Y Axis Label
svg.append('svg:text')
    .attr('class', 'y label')
    .attr('text-anchor', 'middle')
    .attr('y', 0)
    .attr('width', height)
    .attr('transform', 'translate(-' + yAxisSpacing + ',' + height + ') rotate(-90)')
    .text('Y Axis Label')
在这种情况下,

height是图表的高度(svg占用的垂直区域)。上面的代码将在图表的左下角呈现<text>元素,然后将文本相对于该左下角点居中。 width 更改,因此它不会居中,而是从svg的左下角运行。

我猜测如果width等于图表的height,那么其中的文本将垂直居中。情况似乎并非如此 - 或者 - 我需要在SVG中设置一些神奇的display:block类型属性,以便width能够处理<text>元素。

应该怎么做?


根据回复,我使用了javascript路线并修改了以上行(高度/ 2)......

.attr('transform', 'translate(-' + yAxisSpacing + ',' + height / 2 + ') rotate(-90)')

2 个答案:

答案 0 :(得分:5)

width属性对&lt; text&gt;无效在SVG 1.1中。文本将围绕由xy属性定义的x,y位置居中(由于text-anchor = middle)(如果不指定它们,则默认为0)。之后,将应用transform属性。

答案 1 :(得分:1)

你可以用CSS转换来做到这一点。将其添加到您的CSS(通过http://css3please.com):

-webkit-transform: rotate(90deg); 
   -moz-transform: rotate(90deg); 
    -ms-transform: rotate(90deg); 
     -o-transform: rotate(90deg); 
        transform: rotate(90deg); 
           filter: progid:DXImageTransform.Microsoft.Matrix(/* IE6–IE9 */
                 M11=6.123031769111886e-17, M12=-1, M21=1, M22=6.123031769111886e-17, sizingMethod='auto expand');
             zoom: 1;

此处的工作示例 - 查看“css”标签:http://livecoding.io/3492918

相关问题