使用鼠标拖动D3对象时出现“意外值NaN”错误

时间:2014-07-16 14:15:21

标签: d3.js

当我被鼠标要求时,我很难让一些圆圈移动。我正在使用下面的代码(example by Mike Bostock)调整此see jsfiddle here

<!DOCTYPE html>
<html>
<head>
    <title></title>
<script src="http://d3js.org/d3.v3.min.js"></script>
</head>
<body>

<script type="text/javascript">

var points = [
    [100,100],
    [200,300],
    [250,150],
    [300,200],
    [350,350],
    [450,300],
    [450,400]
];

var drag = d3.behavior.drag()
    .origin(function(d) { return d; })
    .on("dragstart", dragstarted)
    .on("drag", dragged)
    .on("dragend", dragended);

var svg = d3.select("body").append("svg")
    .attr("width", 500)
    .attr("height", 500);

svg.selectAll("circle")
    .data(points)
    .enter().append("circle")
    .attr("r", 10)
    .attr("cx", function(d) { return d[0]; })
    .attr("cy", function(d) { return d[1]; })
    .call(drag);

function dragstarted(d) {
  d3.event.sourceEvent.stopPropagation();
  d3.select(this).classed("dragging", true);
}

function dragged(d) {
  d3.select(this).attr("cx", d.x = d3.event.x).attr("cy", d.y = d3.event.y);
}

function dragended(d) {
  d3.select(this).classed("dragging", false);
}

</script>

</body>
</html>

但是在尝试使用鼠标拖动点时出现此错误:

Unexpected value NaN parsing cx attribute.
...},c:t(f),d:function(n,t){return jt(n.getDate(),t,2)},e:function(n,t){return jt(n...
 1)

Unexpected value NaN parsing cy attribute.
...},c:t(f),d:function(n,t){return jt(n.getDate(),t,2)},e:function(n,t){return jt(n...

感谢我出错的想法,并提前感谢。

1 个答案:

答案 0 :(得分:3)

问题在于您没有处理鼠标事件(设置了xy属性),而是处理了拖动事件中的鼠标事件。您可以通过.sourceEvent访问源事件:

d3.select(this).attr("cx", d[0] = d3.event.sourceEvent.x)
               .attr("cy", d[1] = d3.event.sourceEvent.y);

我还将作业更改为d,以便与开始时的工作方式保持一致。完整演示here