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

问题描述:

使用D3,我想要一个Y轴标签,旋转-90º并以Y轴为中心。我认为这将是一块蛋糕,并写下:

Working with D3, I want to have a Y axis label which is rotated -90º and centered on the Y axis. I thought this would be a piece of cake, and wrote the following:

// 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的左下角。

height in this case is the height of the chart (the vertical area occupied by svg). The above code will render a <text> element to the bottom left of the chart, then center the text relative to that bottom left point. The width does not change and thus instead of being centered it runs off the bottom left hand corner of the svg.

我猜测,如果 width 等于图表的 height 那么其中的文本将变为垂直居中。这似乎不是这样 - 或者 - 有一些神奇的 display:block type属性我需要在SVG中设置为了 width $

I had guessed that if the width was equal to the height of the chart, then the text within it would become vertically centered. That doesn't seem to be the case -OR- there is some magic display:block type property I need to set in SVG in order for width to work on the <text> element.

根据回答,我使用javascript路线修改上述行为(height / 2) ...

Based on the responses, I went with a javascript route and modified the above line to be (height/2)...

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


code> width 属性对SVG 1.1中的< text>没有影响。文本将在 x y $ c $定义的x,y位置周围居中(由于text-anchor = c>属性(如果不指定它们,它们默认为0)。之后,应用 transform 属性。

A width attribute has no effect on <text> in SVG 1.1. The text will be centered (due to text-anchor=middle) around the x,y position defined by the x and y attributes (they default to 0 if you don't specify them). After that the transform attribute is applied.