如何在d3.js中拖放svg中的一组矩形?

2024-03-13

我的工作基于this http://bl.ocks.org/biovisualize/1197731拖放示例:

我想拉个团我将两个矩形放在单个组中,现在想要拖放整个组,在我的代码中,拖放适用于单个矩形,但不适用于组。

这是我的代码:

   <!DOCTYPE html>
   <html>
   <head>
   <script type="text/javascript" src="http://mbostock.github.com/d3/d3.js">  </script>

  <title>Drag And Drop</title>
  </head>
  <body>  

    <div id="viz"></div>

     <script type="text/javascript">

     var vizSVG = d3.select("#viz")
              .append("svg")
             .attr("width", 400)
              .attr("height", 300); 





var group =d3.select("svg")
                .append("g")
                .attr("id","group1")
                .attr("x",50)
                .attr("y", 140)
                //.attr("fill", "yellow")
            //  .call(d3.behavior.drag().on("drag", move));


group.append("rect")
    .attr("id", "bluerect")
    .attr("x", 50)
    .attr("y", 140)
    .attr("width", 50)
    .attr("height", 50)
    .attr("stroke", "red")
      .attr("fill", "blue")
      .attr("opacity","0.5")
   .call(d3.behavior.drag().on("drag", move));



    group.append("rect")
    .attr("id", "redrect")
    .attr("x", 110)
    .attr("y", 140)
    .attr("width", 50)
    .attr("height", 50)
    .attr("stroke", "blue")
    .attr("fill", "red")
    .call(d3.behavior.drag().on("drag", move));


    function move(){
        this.parentNode.appendChild(this);

        var dragTarget = d3.select(this);

        dragTarget
        .attr("x", function(){;return d3.event.dx + parseInt(dragTarget.attr("x"))})
        .attr("y", function(){return d3.event.dy +                        parseInt(dragTarget.attr("y"))});
        };

</script>

</body>
</html>

没有x or ySVG 中的属性组元素 https://developer.mozilla.org/en/docs/Web/SVG/Element/g。要定位它们,您必须使用转换 https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/transform:

d3.select(this).attr("transform", "translate(" + x + "," + y + ")")
//the x and y positions here --------------------^  -------^

除此之外,<g>元素只是容器。在下面的演示中(使用transform例如,您必须单击其中一个矩形才能拖动整个组:单击它们之间的空间没有任何效果。

var g = d3.select("g")
  .datum({
    x: 0,
    y: 0
  })
  .call(d3.drag()
    .on("drag", function(d) {
      d3.select(this).attr("transform", "translate(" + 
      (d.x = d3.event.x) + "," + (d.y = d3.event.y) + ")")
    }))
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg>
  <g>
    <rect x="40" y="10" width="50" height="20" fill="teal"></rect>
    <rect x="60" y="40" width="50" height="20" fill="teal"></rect>
    <rect x="30" y="35" width="20" height="20" fill="teal"></rect>
  </g>
</svg>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在d3.js中拖放svg中的一组矩形? 的相关文章

随机推荐