我正在尝试让拖动功能在 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/