D3标签到可拖动的圆圈 [英] D3 Label to draggable circle
本文介绍了D3标签到可拖动的圆圈的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用d3绘制旁边带有标签的圆形元素。
我应该能够在旁边拖动一个带有标签的圆圈。
I'm trying to use d3 to draw circle elements with labels next to them. I should be able to drag a circle with a label following next to it.
任何建议表示赞赏。
https://jsfiddle.net/o3yg8sq1/2/
Any advice is appreciated. 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);
}
推荐答案
由于这是D3 v3,正确的功能是:
Since this is D3 v3, the correct function is:
d3.behavior.drag()
除此之外,要使用相应的文字拖动圆圈,更好的方法是附加 circle
和 text
到一个组:
Besides that, to drag the circle with the corresponding text, a better approach would be appending both circle
and text
to a group:
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/
Here is the updated fiddle: https://jsfiddle.net/gerardofurtado/o3yg8sq1/4/
这篇关于D3标签到可拖动的圆圈的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文