javascript - 在 TreeMap 中将文本元素对齐到中间

标签 javascript css d3.js svg

如何将 text 元素的文本对齐设置为 SVG g 元素(父框)的中心?

比如 html div 元素上的 text-align: center

我尝试通过 D3.js 构建树状图

JSFiddle Demo

这是我尝试的代码:

leaf.append("text")
            .attr("fill", "#fff")
            //.style("text-anchor", "end")
            .attr("width", d => d.x1 - d.x0)
            .attr("height", d => d.y1 - d.y0)
            // .attr("y", 0)
            // .attr("x", 0)
            // .attr("dy", 0)
            .attr("font-size", d => Math.min(d.x1 - d.x0, d.y1 - d.y0) / 6)
            .selectAll("tspan")
            .data(d => d.data.name.split(/(?=[A-Z][^A-Z])/g).concat(format(d.data.volume)).concat(format(d.data.pc)))
            .enter().append("tspan")
            // .style("width", d => d.x1 - d.x0)
            // .style("height", d => d.y1 - d.y0)
             //.style("text-anchor", "middle")
            .attr("dy", "1.1em")
            .attr("x", "5")
            .attr("font-weight", (d, i, nodes) => i === nodes.length - 1 ? "200" : "700")
            .attr("font-size", (d) => d.value)
            .text(d => d);

请查看 JSFiddle 上的示例代码

最佳答案

SVG 元素没有您在代码中使用的任何 HTML 属性。

此处的简单解决方案是设置 x属性到矩形的中间,使用 x0x1由 TreeMap 生成器创建的属性,结合 text-anchor: middle .但是,由于<tspan>绑定(bind)了奇怪的数据元素,我们必须向后弯腰才能从 parent 那里得到数据:

.attr("x", function() {
    const parentData = d3.select(this.parentNode).datum();
    return (parentData.x1 - parentData.x0) / 2;
});

这是您的代码,仅进行了更改:

let data = {
  "name": "topLevel element",
  "children": [{
      "name": "group 1",
      "children": [{
          "name": "first child",
          "volume": 567.2,
          "value": 1250,
          "price": 1201,
          "pc": 1
        },
        {
          "name": "secondary",
          "volume": 7809.1,
          "value": 12450,
          "price": 13201,
          "pc": 2
        },
        {
          "name": "another",
          "volume": 2163.7,
          "value": 12450,
          "price": 13201,
          "pc": 3
        },
        {
          "name": "like svg",
          "volume": 1756.5,
          "value": 12450,
          "price": 13201,
          "pc": 4
        },
        {
          "name": "abc",
          "volume": 1201.7,
          "value": 12450,
          "price": 13201,
          "pc": 5
        }
      ]
    },
    {
      "name": "Group 2",
      "children": [{
          "name": "tripppp",
          "volume": 2999.3,
          "value": 12450,
          "price": 13201,
          "pc": 6
        },
        {
          "name": "pardon",
          "volume": 10398.3,
          "value": 12450,
          "price": 13201,
          "pc": 7
        },
        {
          "name": "world d3",
          "volume": 10150.5,
          "value": 12450,
          "price": 13201,
          "pc": 8
        },
        {
          "name": "other bit",
          "volume": 2652.6,
          "value": 12450,
          "price": 13201,
          "pc": 7
        },
        {
          "name": "rest train",
          "volume": 2894,
          "value": 12450,
          "price": 13201,
          "pc": 4
        },
        {
          "name": "big data",
          "volume": 6281.2,
          "value": 12450,
          "price": 13201,
          "pc": 3
        },
        {
          "name": "relase note",
          "volume": 2431.3,
          "value": 12450,
          "price": 13201,
          "pc": 3
        },
        {
          "name": "seventeen",
          "volume": 2373.5,
          "value": 12450,
          "price": 13201,
          "pc": 2
        },
        {
          "name": "fourth",
          "volume": 1377.1,
          "value": 12450,
          "price": 13201,
          "pc": 1
        }
      ]
    }
  ]
};

let chartDiv = document.getElementById("chart");
let svg = d3.select(chartDiv).append("svg");

var width = chartDiv.clientWidth;
var height = chartDiv.clientHeight;

let chart = () => {
  const root = treemap(filteredData);

  const svg = d3.select("svg");

  svg
    .attr("width", width)
    .attr("height", height)
    .classed("svg-content-responsive", true)
    .attr("preserveAspectRatio", "xMinYMin meet")
    .attr("viewBox", `0 0 ${width} ${height}`);

  const leaf = svg.selectAll("g")
    .data(root.leaves())
    .enter().append("g")
    .attr("transform", d => `translate(${d.x0},${d.y0})`);

  leaf.append("title")
    .text(d => `${d.ancestors().reverse().map(d => d.data.name).join("/")}\n${format(d.value)}`);

  leaf.append("rect")
    .attr("fill", "green")
    .attr("fill-opacity", 1.0)
    // .attr("text-anchor", "start")
    // .attr("dominant-baseline", "central")
    .attr("width", d => d.x1 - d.x0)
    .attr("height", d => d.y1 - d.y0)
    .attr("class", function(d) {
      return "node level-" + d.depth;
    });
  // .on("mouseover", (d) => {		
  //   d3.select(this)
  //     .style("stroke", "yellow")
  //     .style("opacity", 1)
  //  });

  // leaf.append("clipPath")
  //     .attr("id", d => (d.clipUid = ("#clip")).id)
  //     .append("use")
  //     .attr("xlink:href", d => d.leafUid.href);

  leaf.append("text")
    .attr("fill", "#fff")
    //.style("text-anchor", "end")
    // .attr("clip-path", d => d.clipUid)
    .attr("text-anchor", "middle")
    .attr("width", d => d.x1 - d.x0)
    .attr("height", d => d.y1 - d.y0)
    // .attr("y", 0)
    // .attr("x", 0)
    // .attr("dy", 0)
    .attr("font-size", d => Math.min(d.x1 - d.x0, d.y1 - d.y0) / 6)
    .selectAll("tspan")
    .data(d => d.data.name.split(/(?=[A-Z][^A-Z])/g).concat(format(d.data.volume)).concat(format(d.data.pc)))
    .enter().append("tspan")
    // .style("width", d => d.x1 - d.x0)
    // .style("height", d => d.y1 - d.y0)
    // .attr("lengthAdjust" ,"spacingAndGlyphs")
    // .attr("transform", "(250 250 250 250)")
    //.style("text-anchor", "middle")
    // .attr("dominant-baseline", "central")
    .attr("dy", "1.1em")
    .attr("x", function() {
      const parentData = d3.select(this.parentNode).datum();
      return (parentData.x1 - parentData.x0) / 2;
    })
    // .attr("dx", 0)
    // .attr("y", 18)
    // .attr("y", (d, i, nodes) => `${(i === nodes.length ) * 1.3 + 1.2 + i * 1.9}em`)
    .attr("font-weight", (d, i, nodes) => i === nodes.length - 1 ? "200" : "700")
    // .attr("font-family", "Vazir")
    .attr("font-size", (d) => d.value)
    .text(d => d);

  return svg.node();
}
let filteredData = d3.hierarchy(data)
  .sum(d => d.volume)
  .sort((a, b) => b.height - a.height || b.value - a.value);


let treemap = d3.treemap()
  .size([width, height])
  .padding(1)
  .paddingRight(3)
  .round(true);

let format = d3.format(",d");


chart();
* {
  font-family: 'Vazir', sans-serif;
}

/* Make the chart container fill the page using CSS. */

#chart {
  background: #212121;
  position: fixed;
  left: 0px;
  right: 0px;
  top: 0px;
  bottom: 0px;
  font-family: 'Vazir', sans-serif;
}

g text {
  text-shadow: 1px 2px 0 #555;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<link href="https://cdn.rawgit.com/rastikerdar/vazir-font/v19.2.0/dist/font-face.css" rel="stylesheet" type="text/css" />

<div id="chart"></div>

PS:我写“仅进行了更改”,因为您的代码有几个明显的问题,例如分配 width和一个 margin到一个文本元素,我没有触及它。

关于javascript - 在 TreeMap 中将文本元素对齐到中间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55032873/

相关文章:

javascript - 在 JavaScript 中使用 for 循环为音频文件分配不同的源

javascript - 如何使用node.js/electron访问系统文件?

html - 我可以在CSS中链接::first-line和::selection吗?

JavaFX:设置 ProgressIndicator 文本标签的颜色

javascript - D3 将更新选择限制为具有实际更改的条目?

JavaScript 回调风格 - 转向 promise

javascript - 从两个对象的数组生成对象

jquery - 未设置属性时的 CSS 属性选择器(或者我如何只选择非禁用输入[类型 ="text"])

javascript - D3js 随时间绘制?

从下拉过滤器中选择新源时,JavaScript D3 条形图数据将不会更新