d3.js - D3 拖动错误 'Cannot read property x of undefined'

标签 d3.js

我正在尝试让拖动功能在 D3 上工作,并且直接从开发人员的示例中复制了代码。

然而,似乎原点(被点击的内容)没有被正确地传递到变量 d 中,这导致了错误: '无法读取未定义的属性'x''

相关代码:

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);

至于'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 + ')');
        });

关于d3.js - D3 拖动错误 'Cannot read property x of undefined',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24745527/

相关文章:

javascript - json 文件未从 Visual Studio 2013 加载

javascript - 如何使用 d3 让轴在基于网格(热图)的图表上正确显示

json - 带有 JSON 嵌套数据的 D3 分组条形图

javascript - 径向树状图上未显示数据

javascript - d3js 支持的事件类型列表

html - 如何更改 D3 中的 CSS "animation-delay"属性?

javascript - D3.js 中的样式和属性

javascript - d3 js如何从选择中选择

javascript - D3 scale.invert() 没有返回 x 的日期

javascript - 堆积条形图过渡