在d3js的svg圈子内添加svg文本

在d3js的svg圈子内添加svg文本

本文介绍了在d3js的svg圈子内添加svg文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将文本添加到使用d3.js

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

该文本未出现在圆圈内.当我检查元素时,我可以看到text元素已添加到DOM中,并且所需的文本也已添加到text元素中,但是没有出现.我在做什么错了?

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?

以下是代码.

CreateNode创建圆圈

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>

推荐答案

您不能将<text>节点放置在<circle></circle>节点内.您需要一个接一个地堆叠它们.您可以将<circle><text>都添加到<g>元素.试试这个片段

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;

}

这篇关于在d3js的svg圈子内添加svg文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 17:09