D3.js D3拖动错误';无法读取未定义的';

D3.js D3拖动错误';无法读取未定义的';,d3.js,D3.js,我试图在D3上使用拖动功能,并直接从开发人员的示例中复制了代码 但是,似乎原点(正在单击的内容)没有正确传递到变量d中,这导致了错误:'cannotreadproperty'x'of undefined' 有关守则: var drag = d3.behavior.drag() .on("drag", function(d,i) { d.x += d3.event.dx d.y += d3.event.dy d

我试图在D3上使用拖动功能,并直接从开发人员的示例中复制了代码

但是,似乎原点(正在单击的内容)没有正确传递到变量d中,这导致了错误:'cannotreadproperty'x'of undefined'

有关守则:

var drag = d3.behavior.drag()
        .on("drag", function(d,i) {
            d.x += d3.event.dx
            d.y += d3.event.dy
            d3.select(this).attr("transform", function(d,i){
                return "translate(" + [ d.x,d.y ] + ")"
            })
        });

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

var group = svg.append("svg:g")
    .attr("transform", "translate(10, 10)")
    .attr("id", "group");

var rect1 = group.append("svg:rect")
    .attr("rx", 6)
    .attr("ry", 6)
    .attr("x", 5/2)
    .attr("y", 5/2)
    .attr("id", "rect")
    .attr("width", 250)
    .attr("height", 125)
    .style("fill", 'white')
    .style("stroke", d3.scale.category20c())
    .style('stroke-width', 5)
    .call(drag);

通常,在D3中,您从某种数据集创建元素。在你的情况下,你只有一个(也许有一天你会想要更多)。以下是您如何做到这一点:

var data = [{x: 2.5, y: 2.5}], // here's a dataset that has one item in it
    rects = group.selectAll('rect').data(data) // do a data join on 'rect' nodes
        .enter().append('rect') // for all new items append new nodes with the following attributes:
            .attr('x', function (d) { return d.x; })
            .attr('y', function (d) { return d.y; })
            ... // other attributes here to modify 
            .call(drag);
对于
“拖动”
事件处理程序:

var drag = d3.behavior.drag()
        .on('drag', function (d) {

            d.x += d3.event.dx;
            d.y += d3.event.dy;

            d3.select(this)
                .attr('transform', 'translate(' + d.x + ',' + d.y + ')');
        });

奥列格明白了,我只想提一件你可能会做的事

由于您只有一个rect,因此可以使用
.datum()
将数据直接绑定到该rect,而无需计算联接或进行enter选择:

var rect1 = svg.append('rect')
  .datum([{x: 2.5, y: 2.5}])
  .attr('x', function (d) { return d.x; })
  .attr('y', function (d) { return d.y; })
  //... other attributes here
  .call(drag);

谢谢你的澄清!