如何在 d3.js 中拖动 svg 矩形?

how to drag a svg rectangle in d3.js?

这里我在另一个矩形中创建一个名为 resize_icon 的矩形,将其定位在大矩形的右下角 rectangle.I 希望这个 resize_icon 矩形可以在大矩形中自由拖动但它不应越过较大的矩形顶部边缘和左侧边缘,但可以将其拖到其他任何地方。 resize[] 是一个数组,其中包含 resize_icon rectangle.Please 的 id、x 和 y 位置看看下面的拖动代码,请告诉我为什么它不起作用。另外,如果有人可以建议正确的代码,那将非常有帮助。

            c.append('rect').attr('class','resize_icon').attr('fill','#000')
                .attr('id','resize_icon'+i).attr('height',5).attr('width',5)
                .attr('x', x+wd+35).attr('y',y+rectHeight-5).on(drag1)
                .on('click',function(){

                        d3.selectAll(".selected").classed("selected",false);

                        d3.select(this.parentNode).classed("selected",true);

                        resize_rect(i); 


                  });


      var drag1 = d3.behavior.drag().origin(function()
    { 
      var t = d3.select(this);
      return {x: t.attr("x"), y: t.attr("y")};
    })
     .on("dragstart", dragstart)
     .on("drag", dragon)
     .on("dragend", dragstop);


  function dragstart() {
      d3.event.sourceEvent.stopPropagation();
      d3.select(this).classed("drag", true);
    }

  function dragon() {     
      d3.select(this).select('.resize_icon')
                     .attr("x",  d3.event.x)
                     .attr("y", d3.event.y);

      id = d3.select(this).select('.resize_icon').attr("id");
      a = id.replace("resize_icon", "");
      resize[a].x = d3.event.x;
      resize[a].y = d3.event.y;

    }          


  function dragstop() {
   d3.select(this).classed("drag", false);
  }     

这是我在边界之间拖动的代码:

function button_drag2(xLower,xHigher,yLower,yHigher){
    return d3.behavior.drag()
             .origin(function() {
                var g = this;
                return {x: d3.transform(g.getAttribute("transform")).translate[0],
                        y: d3.transform(g.getAttribute("transform")).translate[1]};
            })
            .on("drag", function(d) {

                g = this;
                translate = d3.transform(g.getAttribute("transform")).translate;

                x = d3.event.dx + translate[0],
                y = d3.event.dy + translate[1];

                if(x<xLower){x=xLower;}
                if(x>xHigher){x=xHigher;}
                if(y<yLower){y=yLower;}
                if(y>yHigher){y=yHigher;}

                d3.select(g).attr("transform", "translate(" + x + "," + y + ")");
                d3.event.sourceEvent.stopPropagation();             
            });
}
}

然后调用您的选择:

    var selection = "#rectangle"; //change this to whatever you want to select
    d3.select(selection).call(button_drag2(-100,100,-100,100)); 

// this lets you drag the rectangle 100px left, right, up and down. Change to what ever you want :)

希望这对您有所帮助:)