在 D3.js 个矩形中包含文本

Having text in D3.js rectangles

我正在调用 Ajax 从 API 中获取数据并从返回的数据对象中绘制矩形。

如何在矩形中包含文本(对象 ID)?

        let height = window.innerHeight;
        
        var canvas = d3.select("body")
            .append("svg")
            .attr("width", "100%")
            .attr("height", height)
            
        $(document).ready(function(){
            getData();
        });
        
        function getData() {
            $.ajax({
                url: "http://api.ntjp.se/coop/api/v1/connectionPoints",
                success: function(result){
                    drawRectangles(result);
                }
            });
        }
        
        function drawRectangles(data) {
            
            var rectangles = canvas.selectAll("rect")
                .data(data)
                .enter()
                .append("rect")
                .attr("width", 80)
                .attr("height", 50)
                .style("stroke-width", "1")
                .style("fill", "none")
                .style("stroke", "black")
                .attr("y", function(d, i) { return i * 100});
            
        }

在 SVG 中,像 recttext 这样的形状不能包含其他形状。常规的解决方法是取特殊元素g(组),它本身没有形状,但可以容纳多个形状元素。

然后,您可以为每个 g 元素绘制 recttext,并将 g 元素及其内容准确放置在您想要的位置。

let height = window.innerHeight;

var canvas = d3.select("body")
  .append("svg")
  .attr("width", "100%")
  .attr("height", height);

var data = [
  {
    "id": 4,
    "platform": "NTJP",
    "environment": "PROD",
    "snapshotTime": "2021-12-12T00:05:06+0100"
  },
  {
    "id": 5,
    "platform": "SLL",
    "environment": "PROD",
    "snapshotTime": "2021-12-12T00:00:04+0100"
  },
  {
    "id": 6,
    "platform": "NTJP",
    "environment": "QA",
    "snapshotTime": "2021-12-12T00:05:05+0100"
  },
  {
    "id": 7,
    "platform": "SLL",
    "environment": "QA",
    "snapshotTime": "2021-12-12T00:00:05+0100"
  },
  {
    "id": 8,
    "platform": "NTJP",
    "environment": "TEST",
    "snapshotTime": "2021-12-12T00:05:06+0100"
  }
];

var nodes = canvas.selectAll(".node")
  .data(data)
  .enter()
  .append("g")
  .attr("class", "node")
  .attr("transform", function(_, i) {
    return `translate(0, ${i * 100})`;
  })

nodes
  .append("rect")
  .attr("width", 80)
  .attr("height", 50)
  .style("stroke-width", "1")
  .style("fill", "none")
  .style("stroke", "black");

nodes
  .append("text")
  // To make the `text` node have access to the data related to the `g` node
  .datum(function(d) { return d; })
  .attr("y", 25)
  .attr("x", 40)
  .attr("dy", "0.5em")
  .attr("text-anchor", "middle")
  .text(function(d) { return d.platform; });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/6.2.0/d3.min.js"></script>