2017-06-03 57 views
-1

我有這段代碼,其中畫了圓圈,我需要在每個圓圈內放置一個文本,我還想知道如何將一定大小放到圓圈的每個元素中。 非常感謝。將文字置於圓圈中間使用。 d3.js

svg = d3.select(selector) 
    .append('svg') 
    .attr('width', width) 
    .attr('height', height); 

    // Bind nodes data to what will become DOM elements to represent them. 
    bubbles = svg.selectAll('.bubble') 
    .data(nodes, function (d) { return d.id; }); 

    // Create new circle elements each with class `bubble`. 
    // There will be one circle.bubble for each object in the nodes array. 
    // Initially, their radius (r attribute) will be 0. 



    bubbles.enter().append('circle') 
    .classed('bubble', true) 
    .attr('r', 0) 
    .attr('fill', function (d) { return fillColor(d.group); }) 
    .attr('stroke', function (d) { return d3.rgb(fillColor(d.group)).darker(); }) 
    .attr('stroke-width', 2) 
    .on('mouseover', showDetail) 
    .on('mouseout', hideDetail); 


    // Fancy transition to make bubbles appear, ending with the 
    // correct radius 
    bubbles.transition() 
    .duration(2000) 
    .attr('r', function (d) { return d.radius; }); 

回答

0

較好的做法將是爲每個氣泡創建一個組元素,因爲它們將被由兩個部分組成 - 一個圓和文本。

// Bind nodes data to what will become DOM elements to represent them. 
bubbles = svg.selectAll('.bubble') 
    .data(nodes, function(d) { 
    return d.id; 
    }) 
    .enter() 
    .append('g') 
    .attr("transform", d => `translate(${d.x}, ${d.y})`) 
    .classed('bubble', true) 
    .on('mouseover', showDetail) 
    .on('mouseout', hideDetail) 

之後,圓和文本可以追加:

circles = bubbles.append('circle') 
    .attr('r', 0) 
    .attr('stroke-width', 2) 


texts = bubbles.append('text') 
    .attr('text-anchor', 'middle') 
    .attr('alignment-baseline', 'middle') 
    .style('font-size', d => d.radius * 0.4 + 'px') 
    .attr('fill-opacity', 0) 
    .attr('fill', 'white') 
    .text(d => d.text) 

// Fancy transition to make bubbles appear, ending with the 
// correct radius 
circles.transition() 
    .duration(2000) 
    .attr('r', function(d) { 
    return d.radius; 
    }); 

,隱藏/顯示文本時,可以使用fill-opacity屬性,並將其設置0當文本應該被隱藏,1如果應顯示:

function showDetail(d, i) { 
    d3.select(this.childNodes[1]).attr('fill-opacity', 1) 
} 

function hideDetail(d, i) { 
    d3.select(this.childNodes[1]).attr('fill-opacity', 0) 
} 

例如:https://jsfiddle.net/r880wm24/

+0

的感謝!但在我的真實例子中,它不起作用.. http://plnkr.co/edit/2BCVxQ5n07Rd9GYIOz1c?p=preview – yavg