如何使用 D3 移动(拖放)多个形状

Tho*_*ues 4 svg drag-and-drop move d3.js

如何使用 d3 移动(拖放)多个形状。

我尝试将一些形状放入 svg 中并移动 svg - 这有效但不顺利。 这是我到目前为止得到的

<html>
<head>
<script type="text/javascript" src="d3.v3.min.js"></script>
<title>Creating SVG groups with D3.js</title>
</head>
<body>
<script type="text/javascript">

// http://tutorials.jenkov.com/svg/g-element.html

d3image = d3.select("body");

svgcanvas = d3image.append("svg:svg").attr("width", 700).attr("height", 500);

svg1 = svgcanvas.append("svg:svg").attr("x", 100).attr("y", 100);

circle1 = svg1.append("svg:circle")
.attr("cx", 40)
.attr("cy", 40)
.attr("r", 37.5)
.call(d3.behavior.drag().on("drag", move));

rect1 = svg1.append("svg:rect")
.attr("x",0)
.attr("y",50)
.attr("width",100)
.attr("height",75)
.call(d3.behavior.drag().on("drag", move));

text1 = svg1.append("svg:text")
.text("Group 1")
.attr("x", 0)
.attr("y", 70)
.style("stroke", "orange")
.style("stroke-width", 1)
.style("font-size", "150%")
.style("fill", "orange")
.call(d3.behavior.drag().on("drag", move));

function move(){
    var parent = d3.select(this.parentNode);
    parent.attr("x", function(){return d3.event.dx + parseInt(parent.attr("x"))})
            .attr("y", function(){return d3.event.dy +             parseInt(parent.attr("y"))});
};

</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

有什么建议么?

Jas*_*ies 5

需要在拖动过程中更新其位置的选择上调用拖动行为。在您的代码中,您正在更新父节点的位置,这会导致奇怪的“抖动”,因为拖动位置本身是相对于父节点的。

例如,您可以将move上面的函数替换为:

function move() {
  d3.select(this)
      .attr("transform", "translate(" + d3.event.x + "," + d3.event.y + ")");
}
Run Code Online (Sandbox Code Playgroud)