我还是d3.js的新手,我在处理鼠标拖动事件时遇到了麻烦。我已经设置了框架,用一个可以拖动的圆圈进行x-y绘图。当我拖动它时,我可以让它移动圆圈,但只有在我尝试拖动它之后,它才会无意中选择窗口的其余部分...不是我想到的。
我尝试将代码放在jsfiddle中,但鼠标交互似乎并不适用于那里:
http://jsfiddle.net/noiseinthestreet/jjk9ts10/1/
以下是代码:
var canvasWidth = 700, canvasHeight = 700;
var margin = 20;
var innerwidth = canvasWidth - margin*2;
var innerheight = canvasHeight - margin*2;
var xScale = d3.scale.linear().domain([-10,10]).range([0+margin,canvasWidth-margin]);
var yScale = d3.scale.linear().domain([10,-10]).range([0+margin,canvasHeight-margin]);
var xAxis = d3.svg.axis().tickSize(1, 0, 0).scale(xScale).orient("bottom");
var yAxis = d3.svg.axis().tickSize(1, 0, 0).scale(yScale).orient("left");
var impos = [xScale(5), yScale(5)];
var mousedownFlag=0
var dataArray = [-3, 0, 3];
var canvas = d3.select("body")
.append("svg").attr("width",canvasWidth).attr("height",canvasHeight);
canvas.append("g")
.append("svg:image").attr("width","660").attr("height","660")
.attr("x", xScale(-10)).attr("y", yScale(10));
canvas.append("g").call(xAxis).attr("transform","translate(0,680)");
canvas.append("g").call(yAxis).attr("transform","translate(20,0)");
function mouseDrag(d) {
var x = d3.event.x,
y = d3.event.y;
if(x>0 && y>0)
d3.select("circle").attr("cx", x).attr("cy", y);
}
function mouseClick(d) {
var x = d3.event.x,
y = d3.event.y;
d3.select("circle").attr("cx", x).attr("cy", y);
}
// draggable circle
var circle = canvas.append("circle")
.attr("cx", 30)
.attr("cy", 30)
.attr("r", 20)
.on("click", mouseClick)
.on("drag", mouseDrag);
尽管如此,我希望这个小提琴能够足够接近,以便真正知道他们正在做什么的人(即不是我)将能够快速指出我需要改变的东西: )
答案 0 :(得分:0)
感谢Pablo Navarro的建议,我用d3.behavior.drag()涂了几分钟并让它运转起来。谢谢!以下是我必须更改的相关代码部分:
var drag = d3.behavior.drag()
.on("drag",function(){d3.select("circle").attr("cx",d3.event.x).attr("cy",d3.event.y);});
...
// draggable circle
var circle = canvas.append("circle")
.attr("cx", 30)
.attr("cy", 30)
.attr("r", 20)
.call(drag);