[英]Adding svg text inside svg circle in d3js
我正在嘗試使用d3.js
將文本添加到SVG
制成的圓中
文本未出現在圓圈內。 當我檢查元素時,我可以看到text元素已添加到DOM中,並且所需的文本也已添加到text元素中,但是沒有出現。 我究竟做錯了什么?
以下是代碼。
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>
元素。 試試這個片段
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.