Adding svg text inside svg circle in d3js

2020-05-02 09:11发布

问题:

I am trying to add text into a circle made in SVG with d3.js

The text is not appearing inside the circle. When I inspect the element I can see that the text element has been added in the DOM and the required text has also been added inside the text element, But it does not appear. What am I doing wrong?

Following is the code.

CreateNode creates circle

var Xvalue = 100;
var Yvalue = 100;

$(document).ready(function() {
  var graphContainer =  d3.select("body").append("svg").attr("width", 500).attr("height", 600).attr("class","graph-container");
  var root = CreateNode(1,"root","head","main");
});

function CalculateX(nodeType) {
  if(nodeType=="main") {
    return(Xvalue+30);
  }
}

function CalculateY(nodeType) {
  if(nodeType=="main") {
    return(Yvalue);
  }
}

function CreateNode(nodeId,label,className,nodeType) {   
  var node = d3.select("svg")
  .append("circle")
  .attr("cx", CalculateX(nodeType))
  .attr("cy", CalculateY(nodeType))
  .attr("r",40)
  .style("fill","none")
  .style("stroke","#ccc")
  .attr("nodeId",nodeId)
  .attr("class",className);

  node =  node.append("text")
  .attr("x", CalculateX(nodeType))             
  .attr("y", CalculateY(nodeType))
  .attr("text-anchor", "middle")  
  .style("font-size", "14px")
  .attr('fill','#cccccc')
  .text(label);
  return node;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.0/d3.min.js"></script>

回答1:

You cannot place the <text> node inside the <circle></circle> node. You need to stack them one after the other. You can add both <circle> and <text> to a <g> element. Try this snippet

function CreateNode(nodeId,label,className,nodeType)
{   
  var node = d3.select("svg").append('g');

  node.append("circle")
   .attr("cx", CalculateX(nodeType))
   .attr("cy", CalculateY(nodeType))
   .attr("r",40)
   .style("fill","none")
   .style("stroke","#ccc")
   .attr("nodeId",nodeId)
   .attr("class",className);

   node.append("text")
    .attr("x", CalculateX(nodeType))             
    .attr("y", CalculateY(nodeType))
    .attr("text-anchor", "middle")  
    .style("font-size", "14px")
    .attr('fill','#cccccc')
    .text(label);

    return node;

}