围绕圆圈旋转文本

时间:2016-07-15 15:06:28

标签: d3.js svg

我想旋转一些我围绕圆圈定位的文字(数字),如下所示:

enter image description here

要应用旋转,我尝试过这样做:.attr("transform", function(d, i) { return "rotate(" + (-90 + ((360 / dial.length) * i)) + ", 135, 135)"; });但是它会把所有东西都抛出来。

这是fiddle

2 个答案:

答案 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,并相应地更改了xy位置。

&#13;
&#13;
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;
&#13;
&#13;

这是小提琴:https://jsfiddle.net/gerardofurtado/24heuL1h/1/