简体   繁体   English

D3标签到可拖动的圆圈

[英]D3 Label to draggable circle

I'm trying to use d3 to draw circle elements with labels next to them. 我正在尝试使用d3绘制旁边带有标签的圆形元素。 I should be able to drag a circle with a label following next to it. 我应该可以在旁边拖动一个带有标签的圆圈。

Any advice is appreciated. 任何建议表示赞赏。 https://jsfiddle.net/o3yg8sq1/2/ 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);
    }

Since this is D3 v3, the correct function is: 由于这是D3 v3,正确的功能是:

d3.behavior.drag()

Besides that, to drag the circle with the corresponding text, a better approach would be appending both circle and text to a group: 除此之外,要使用相应的文本拖动圆圈,更好的方法是将circletext附加到组:

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")

And call the drag to that group: 并将拖动调用到该组:

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 + ")"
    })
}

Here is the updated fiddle: https://jsfiddle.net/gerardofurtado/o3yg8sq1/4/ 这是更新的小提琴: https//jsfiddle.net/gerardofurtado/o3yg8sq1/4/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM