5
\$\begingroup\$

I'm using the following function to enable dragging on an SVG group.

var dragcontainer = d3.drag()
                        .on("start", function () { })
                        .on("drag", function (d, i) {

                            this.x = this.x || 0;
                            this.y = this.y || 0;

                            this.x += d3.event.dx;
                            this.y += d3.event.dy;
                            d3.select(this).attr("transform", "translate(" + this.x + "," + this.y + ")");

                        })
                        .on("end", function () {});

d3.select("#svg-group-id").call(dragcontainer);

Is there a better (simpler) way to achieve this than manually updating the translate destination?

\$\endgroup\$
  • \$\begingroup\$ Zoom and drag made possible with d3.behavior.zoom: jsfiddle.net/9cWWW/6. Could this work for you? \$\endgroup\$ – MarkokraM Sep 23 '16 at 11:56
2
\$\begingroup\$

Yes, there is a simpler way to achieve this: just use d3.event.x and d3.event.y, holding their values in the bound data.

Thus, your drag function can be reduced to only this:

var dragcontainer = d3.drag()
    .on("drag", function(d, i) {
        d3.select(this).attr("transform", "translate(" + (d.x = d3.event.x) + ","
        + (d.y = d3.event.y) + ")");
    })

And, since you don't use them, just drop your "start" and "end" listeners.

Here is the demo (click and drag the group around):

var dragcontainer = d3.drag()
  .on("drag", function(d, i) {
    d3.select(this).attr("transform", "translate(" + (d.x = d3.event.x) + "," + (d.y = d3.event.y) + ")");
  });
var g = d3.select("g").datum({x: 0, y: 0}).call(dragcontainer)
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg style="border: 1px solid gray">
  <g>
    <circle cx="50" cy="50" r="20" fill="teal"></circle>
    <circle cx="100" cy="50" r="20" fill="tomato"></circle>
    <circle cx="150" cy="50" r="20" fill="tan"></circle>
  </g>
</svg>

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.