2014-07-14 24 views
2

我想要獲得拖動功能在D3上工作,並直接從開發人員的示例中複製代碼。D3拖動錯誤'不能讀取屬性x的undefined'

不過似乎起源(被點擊的是什麼)沒有被正確地傳遞到變量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); 

回答

7

通常,在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 + ')'); 
     }); 
4

奧列格拿到了它,我只是想提一提,你可能在你的情況做一兩件事。

既然你只有一個單一的矩形,你可以直接將數據綁定到它與.datum(),而不是與計算的聯接或者具有輸入選擇打擾:

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

謝謝你的澄清! – jetlej

相關問題