我正在尝试用线条从左到右和从右到左连接圆圈。但我还没能让线条贴在目标圈上。 如果不是同一个线,那些线就会粘在随机圆上。 cD是右圆; cG是左圆; cS是源圈,表示该行来自的圆圈
我对“mousemove”功能的研究是取得了一些进展。我在想,如果鼠标位于任何不是源圆的圆上,则该线的X2,y2应取cx,cy为圆的中心。但这也会使线条粘到与截图中看到的相同颜色的圆圈上。
这是渲染代码:
function setPoints(){
//ajoute les points
svgContainer = d3.select("#centre").append("svg")
.attr("id", "svgGlobal")
.attr("width", "100%")
.attr("height", "100%")
.on("mouseup", mouseupVide);
//récupère les cordonnées du svg
var rectSVG = document.getElementById("svgGlobal").getBoundingClientRect();
//ajoute les points à droites
var circlesDroite = svgContainer.selectAll(".cD")
.data(dataset.droite)
.enter()
.append("circle")
.attr("class", "cD")
.attr("cx", function (d) {
return rectSVG.width - r;
})
.attr("cy", function (d) {
var rect = document.getElementById(d).getBoundingClientRect();
return rect.top-rectSVG.top+(rect.height/2);
})
.attr("r", r)
.on("mousedown", mousedown)
.on("mouseup", mouseup)
.on("mouseover", mouseoverCircle)
.on("mouseout", mouseoutCircle)
;//.style("fill", "red");
//ajoute les points à gauche
var circlesGauche = svgContainer.selectAll(".cG")
.data(dataset.gauche)
.enter()
.append("circle")
.attr("class", "cG")
.attr("cx", function (d) {
return r;
})
.attr("cy", function (d) {
var rect = document.getElementById(d).getBoundingClientRect();
return rect.top-rectSVG.top+(rect.height/2);
})
.attr("r", r)
.on("mousedown", mousedown)
.on("mouseup", mouseup)
.on("mouseover", mouseoverCircle)
.on("mouseout", mouseoutCircle)
;//.style("fill", "green");
}
这些是鼠标功能
function mousedown()
{
var m = d3.mouse(this);
var c = d3.select(this);
c.attr("class", "cS");
line = svgContainer.append("line")
.attr("x1", c.attr("cx"))
.attr("y1",c.attr("cy"))
.attr("x2", m[0])
.attr("y2", m[1]);
lineEnd = false;
svgContainer.on("mousemove", mousemove);
}
function mousemove() {
var m = d3.mouse(this);
var c = d3.select(this);
line.attr("x2", m[0]);
line.attr("y2", m[1]);
if(d3.select(this).attr("class") == "cS") {
line.attr("x2", m[0]);
line.attr("y2", m[1]);
} else {
line.attr("x2", d3.select(this).attr("cx"));
line.attr("y2", d3.select(this).attr("cy"));
}
}
function mouseup() {
var m = d3.mouse(this);
var c = d3.select(this);
//c.attr("r", r*2);
if (lineEnd==true){
if (Math.sqrt((m[0]-c[0])*(m[0]-c[0]) + (m[1]-c[1])*(m[1]-c[1])) < c.attr("r")){
line.attr("x2", c[0])
.attr("y2", c[1]);
}
}
}
function mouseupVide() {
if(!lineEnd)line.remove();
else lineEnd = false;
svgContainer.on("mousemove", null);
}
function mouseoverCircle(){
var c = d3.select(this);
c.attr("class", "cS");
//console.log(c.attr("r"));
lineEnd = true;
}
function mouseoutCircle(d){
var c = d3.select(this);
if(d.substr(0,3)=='acd')
c.attr("class", "cD");
else
c.attr("class", "cG");
lineEnd = false;
}