围绕圆形旋转文本

3
我想要将我已经在圆周上定位的一些文本(数字)旋转,使其呈现如下效果:

enter image description here

为了应用旋转,我尝试了这个:.attr("transform", function(d, i) { return "rotate(" + (-90 + ((360 / dial.length) * i)) + ", 135, 135)"; }); 但它会使一切混乱。
这里有一个fiddle
2个回答

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
我找到的解决方案是更改rotate的附加值,其中<x><y>值表示用作旋转中心点的坐标。
rotate(<a> [<x> <y>])

我更改了<x><y>center,并相应地更改了您的xy位置。

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 + ")"; });
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

这是代码片段:https://jsfiddle.net/gerardofurtado/24heuL1h/1/


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接