2017-03-02 105 views
0

我該如何爲每個圈子添加文字標籤?我的意思是我想旋轉這個文本,改變顏色和類似的東西?我想沒有JSON的解決方案,我想從添加文字標籤

var w = 300, 
 
    h = 300; 
 

 
var data = { 
 
    name: "root", 
 
    children: [{ 
 
     name: '1', 
 
     size: 70 
 
    }, 
 
    { 
 
     name: '2', 
 
     size: 90 
 
    }, 
 
    { 
 
     name: '3', 
 
     size: 70 
 
    }, 
 
    { 
 
     name: '4', 
 
     size: 40 
 
    }, 
 
    { 
 
     name: '5', 
 
     size: 70 
 
    }, 
 
    { 
 
     name: '6', 
 
     size: 20 
 
    }, 
 
    { 
 
     name: '7', 
 
     size: 70 
 
    }, 
 
    ] 
 
} 
 

 
var canvas = d3.select("#canvas") 
 
    .append("svg:svg") 
 
    .attr('width', w) 
 
    .attr('height', h); 
 

 
var nodes = d3.layout.pack() 
 
    .value(function(d) { 
 
    return d.size; 
 
    }) 
 
    .size([w, h]) 
 
    .nodes(data); 
 

 
// Get rid of root node 
 
nodes.shift(); 
 

 
canvas.selectAll('circles') 
 
    .data(nodes) 
 
    .enter().append('svg:circle') 
 
    .attr('cx', function(d) { 
 
    return d.x; 
 
    }) 
 
    .attr('cy', function(d) { 
 
    return d.y; 
 
    }) 
 
    .attr('r', function(d) { 
 
    return d.r; 
 
    }) 
 
    .attr('fill', 'white') 
 
    .attr('x', 0) 
 
    .attr('y', 0) 
 
    .attr('width', 6) 
 
    .attr('height', 6); 
 

 
var textLabels = text 
 
    .attr("x", function(d) { 
 
    return d.cx; 
 
    }) 
 
    .attr("y", function(d) { 
 
    return d.cy; 
 
    }) 
 
    .text(function(d) { 
 
    return "(" + d.cx + ", " + d.cy + ")"; 
 
    }) 
 
    .attr("font-family", "sans-serif") 
 
    .attr("font-size", "20px") 
 
    .attr("fill", "red");
#canvas { 
 
    width: 300px; 
 
    height: 300px; 
 
    background-color: red; 
 
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script> 
 

 

 
<div id="canvas"></div>

我嘗試了很多東西,但不起作用antything得到這個數據..

+1

你是什麼意思_solution沒有json_ – Cyril

回答

2

我不知道你的意思是「沒有json」,但我修復了你的文本標籤。

你在上面的代碼中調用了text這是沒有定義的,我想你打算在這裏附加它。

您需要爲text標籤創建一個佔位符,再次遍歷數據,然後附加文本。

canvas.selectAll("text") 
    .data(nodes) 
    .enter() 
    .append("text") 
    .attr("x", function(d) { 
    return d.x; 
    }) 
    .attr("y", function(d) { 
    return d.y; 
    }) 
    .text(function(d) { 
    return "(" + d.x + ", " + d.y + ")"; 
    }) 
    .attr("text-anchor", "middle") 
    .attr("font-family", "sans-serif") 
    .attr("font-size", "10px") 
    .attr("color", "black");