【发布时间】:2015-06-13 22:50:53
【问题描述】:
我正在尝试用 d3 中的一条线连接两个矩形。行为应该是这样的,
假设我们有矩形A和B。我们必须首先单击一个矩形,当我们移动鼠标时,线必须随着鼠标移动,当我单击B时。线应该连接A和B。
这就是我现在所拥有的。我无法更新线路。它不断添加新的线对象。
<svg id="main" width="500" height="500" style="background-color: red">
<rect id="a" x="100" y="100" height="50" width="50" style="fill: blue"></rect>
<rect id="b" x="400" y="400" height="50" width="50" style="fill: blue"></rect>
</svg>
<script>
d3.select("#a")
.on('click', function(d){
var elem = d3.select(this);
var mouseLoc = d3.mouse(this);
d3.select("#main")
.on('mousemove', function(d){
// d3.select('#li').remove();
d3.select('#main').append("line")
.attr('id', 'li')
.attr('x1', elem.attr('x'))
.attr('y1', elem.attr('y'))
.attr('x2', d3.mouse(this)[0]+5)
.attr('y2', d3.mouse(this)[1]+5)
.attr("stroke", function (d) { return "black"; })
.style("stroke-width", function(d) { return "1 px"; });
})
;
console.log('clicked');
});
</script>
【问题讨论】:
标签: javascript svg d3.js