我想旋转一些我围绕圆圈定位的文字(数字),如下所示:
要应用旋转,我尝试过这样做:.attr("transform", function(d, i) { return "rotate(" + (-90 + ((360 / dial.length) * i)) + ", 135, 135)"; });
但是它会把所有东西都抛出来。
这是fiddle。
答案 0 :(得分:2)
来自@GerardoFurtado的解决方案很好,但是如果你将所有内容放在原点,你可以简化代码。
随意接受他的回答。我只想指出一些效率。
var width = height = 300,
circleRadius = (width / 2) * .8,
digitRadius = (width / 2) * .9;
svg = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
// Everything inside the group is centred at the origin and we use
// a transform on the group to move the whole group to the centre of the SVG
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
svg.append("circle")
.attr("r", circleRadius)
.style("fill", "none")
.style("stroke", "black");
dial = [1, 2, 3, 4, 5, 6, 7, 8];
// Position text at X=radius, Y=0 and rotate around the origin to get final position
svg.selectAll("text")
.data(dial)
.enter()
.append("text")
.attr("x", digitRadius)
// tweak digit Y position a little to ensure it's centred at desired position
.attr("y", "0.4em")
.text(function(d, i) { return d; })
.attr("transform", function(d, i) { return "rotate(" + (-90 + ((360 / dial.length) * i)) + ")"; });
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
答案 1 :(得分:1)
我找到的解决方案是更改rotate
的其他值,其中<x>
和<y>
值表示用作旋转中心的点的坐标。:
rotate(<a> [<x> <y>])
我为<x>
更改了<y>
和center
,并相应地更改了x
和y
位置。
var width = height = 300,
radius = center = (width / 2) * .9;
svg = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", function(d) { return "translate(" + (radius * .1) / 2 + "," + (radius * .1) / 2 + ")"; });
svg.append("circle")
.attr("cx", radius)
.attr("cy", radius)
.attr("r", radius*.9)
.style("fill", "none")
.style("stroke", "black");
// Calculate dial start and end.
dial = [1, 2, 3, 4, 5, 6, 7, 8];
svg.selectAll("text")
.data(dial)
.enter()
.append("text")
.attr("x", function(d, i) { return center + radius * Math.cos(2 * Math.PI / dial.length-0.75); })
.attr("y", function(d, i) { return center + radius * Math.sin(2 * Math.PI / dial.length-0.75); })
.text(function(d, i) { return d; })
.attr("transform", function(d, i) { return "rotate(" + (-90 + ((360 / dial.length) * i)) + "," + center + "," + center + ")"; });
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
&#13;