简体   繁体   English

使用D3JS在圆弧内旋转文本

[英]Text rotation within an arc using D3JS

I've created a chart using D3JS, and it's working fine. 我用D3JS创建了一个图表,它工作正常。 However, I want to set a different text rotation within the arcs, and I'm not being able to figure out how. 但是,我想在圆弧内设置一个不同的文本旋转方式,但我不知道该怎么做。

The left chart contains the current alignment. 左侧图表包含当前对齐方式。 The right chart is the desired one. 正确的图表是理想的图表。 Only the text rotation is missing. 仅缺少文字旋转。

Current and Desired Text alignment - Image 当前和期望的文本对齐 - 图像

HTML Code and Json Data: https://dl.dropboxusercontent.com/u/75479878/HtmlAndJson.zip HTML代码和Json数据: https//dl.dropboxusercontent.com/u/75479878/HtmlAndJson.zip

I think that's the piece of code I need to change, but don't know how: 我认为这是我需要更改的代码,但是不知道如何:

function computeTextRotation(d) {
  return (x(d.x + d.dx / 2) - Math.PI / 2) / Math.PI * 180;
}

You need to rework a few things to get the effect you want. 你需要重做几件事来获得你想要的效果。 The text labels are rotated with respect to the whole figure. 文本标签相对于整个图旋转。 Instead, place them in the center of each arc using arc.centroid and then rotate them "locally". 而是使用arc.centroid将它们放置在每个弧的中心,然后“局部”旋转它们。

First, here's the angle you desire (the angle of the arc): 首先,这是您想要的角度(圆弧的角度):

function computeTextRotation(d) {
  return (x(d.x + d.dx / 2)) / Math.PI * 180;
}

Second, here's the placement and rotate call: 其次,这是放置和旋转调用:

  var text = g.append("g")
    .attr("transform", function(d){
      return "translate(" + arc.centroid(d) + ")";
    })
    .append("text")
    .attr("transform", function(d) {
      return d.parent ? "rotate(" + computeTextRotation(d) + ")" : "";
    })
    .style("text-anchor", "middle")
    .attr("dy", ".35em") // vertical-align
    .style("fill", function(d) {
      return d.textcolor ? d.textcolor : "#000";
    })
    .text(function(d) {
      if (d.parent) {
        return d.name;
      } else {
        aux = d.description;
        return "";
      }
    });

Working example here 这里的工作示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM