簡體   English   中英

如何在D3圓包中匹配文本寬度與圓圈大小

[英]How to match text width to circle size in D3 circle pack

使用D3我會顯示一堆不同大小的圓圈,每個圓圈都填充文字。 我堅持找到正確的字體大小,以便文本在圓圈中適合,取決於它的大小和文本的長度。 長篇文章可能會分成更多行。 這是我的代碼:

var data = {
    "name": "",
    "children": [
        { "name": "This is a tag", "value": 242 },
        { "name": "Circle", "value": 162 },
        { "name": "Tree", "value": 80 },
        { "name": "My sentence is very long and needs breaks", "value": 80 },
    ]
}

var diameter = 300,
    format = d3.format(",d");

var bubble = d3.layout.pack()
    .sort(null)
    .size([diameter, diameter])
    .padding(1.5);

var svg = d3.select("body").append("svg")
    .attr("width", diameter)
    .attr("height", diameter)
    .attr("class", "bubble");

d3.json(data, function(error, root) {
  var node = svg.selectAll(".node")
      .data(bubble.nodes(data)
      .filter(function(d) { return !d.children; }))
    .enter().append("g")
      .attr("class", "node")
      .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });

  node.append("circle")
      .attr("r", function(d) { return d.r; })
      .style("fill", function(d) { return '#f88' });

  // text part
  node.append("text")
      .attr("dy", ".3em")
      .style("text-anchor", "middle")
      .style("font-size", function(d) { return Math.round(d.r/3)+'px'; })
      .text(function(d) { return d.name.substring(0, d.r / 3); });
});

d3.select(self.frameElement).style("height", diameter + "px");

我在http://jsfiddle.net/L4nMx/上創建了一個小提琴。我想我應該計算文本的寬度並修改字體大小,直到它匹配圓圈的大小或類似的東西。 或者是否有任何“strech”功能可以輕松實現這一目標?

這個解決方案現在對我來說很好。 這不是准確的數學,但無論如何都適合。

http://jsfiddle.net/L4nMx/3/上查看它的實際操作

  .style("font-size", function(d) {
      var len = d.name.substring(0, d.r / 3).length;
      var size = d.r/3;
      size *= 10 / len;
      size += 1;
      return Math.round(size)+'px';
  })
  .text(function(d) {
      var text = d.name.substring(0, d.r / 3);
      return text;
  });

下一步是將長文本分成多行,這樣你就可以在這種情況下擴大字體大小,但我沒有設法解決這個問題。 在SVG中這並不容易,因為簡單的換行是不可能的。 也許這里可以添加問題評論中的包裝解決方案 - 不知何故......

有這個bl.ocks https://bl.ocks.org/mbostock/1846692

這基本上是

 node.append("circle")
      .attr("r", function(d) { return d.r; });

  node.append("text")
      .text(function(d) { return d.name; })
      .style("font-size", function(d) { return Math.min(2 * d.r, (2 * d.r - 8) / this.getComputedTextLength() * 24) + "px"; })
      .attr("dy", ".35em");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM