2016-10-05 2 views
3

Я пытаюсь использовать d3 для рисования элементов круга с ярлыками рядом с ними. Я должен уметь перемещать круг с меткой рядом с ним.D3 Ярлык для перетаскиваемого круга

Любые советы приветствуются. https://jsfiddle.net/o3yg8sq1/2/

const svg = d3.select('svg'), 
     width = +svg.attr('width'), 
     height = +svg.attr('height'); 

    const node = svg.append('g') 
     .attr('class', 'nodes') 
     .selectAll('circle') 
     .data([{1:1},{2:2}]) 
     .enter().append('circle') 
     .attr('r', 15) 
     .attr('cx', function (d, i) { return Math.random() * 100; }) 
     .attr('cy', function (d, i) { return Math.random() * 100; }) 
     .call(d3.drag() 
      .on('drag', dragmove)); 

    svg.selectAll('.nodes') 
     .append('text') 
     .text(function(d){return 'test';}) 

    function dragmove(d) { 
     d3.select(this).attr('cx', d3.event.x); 
     d3.select(this).attr('cy', d3.event.y); 
    } 

ответ

2

Поскольку это D3 v3, правильная функция:

d3.behavior.drag() 

Кроме того, чтобы перетащить круг с соответствующим текстом, лучшим подходом было бы добавление как circle и text к группа:

const node = svg.selectAll('.g') 
    .data([{1:1},{2:2}]) 
    .enter().append('g').attr("transform", function(){ 
     return "translate(" + Math.random() * 100 + "," 
     + Math.random() * 100 + ")" 
}); 

node.append("circle").attr('r', 15); 

node.append('text') 
    .attr("dx", 16) 
    .text("test") 

И вызвать сопротивление в этой группе:

node.call(d3.behavior.drag() 
    .on('drag', dragmove)); 

function dragmove(d) { 
    d3.select(this).attr("transform", function(){ 
     return "translate(" + d3.event.x + "," + d3.event.y + ")" 
    }) 
} 

Вот дополненная скрипку: https://jsfiddle.net/gerardofurtado/o3yg8sq1/4/

Смежные вопросы