Find distance from drag and drop in D3

I have a set of D3 elements (they are text nodes, but I think it doesn't matter what type) to which I have attached drag and drop behavior:

        paragraphs.enter().append("text")
            .text(function (d, i) { return d })
            .attr("x", function (d, i) { return (i + 1) * 32 })
            .attr("y", function (d, i) { return (i + 1) * 16 })
            .attr("fill", color)
            .call(d3.drag()
                .on("start", dragstarted)
                .on("drag", dragged)
                .on("end", dragended))

I would like the drag and drop behavior to be aware of how far the user dragged it using dragstart. Currently, I add attrin dragstarted, which marks the starting position, then draggedchecks the current position during and calculates it this way.

Is there a way to find the distance traveled since the drag startand drop without calculating it, simply from the drag events directly? I watched dx/ dy, but they seem to be calculated only from the moment of the last drag event, so the value is always in the lower digits.

+4
source share
1 answer

According to the API , these are fields opened by an event object during a drag event:

  • target is the behavior associated with this.
  • type - string "start", "drag" or "end"; see drag.on.
  • subject - the drag object defined by the drag.subject function.
  • x is the new x-coordinate of the object; see drag.container.
  • y - y- ; . drag.container.
  • dx - x- .
  • dy - y- .
  • - "" .
  • active - ( , ).
  • sourceEvent - , mousemove touchmove.

, , .

, , " " .

"" "" :

d3.drag().on("start", function(d) {
    d.startX = d.x;
    d.startY = d.y;
}).on("drag", function(d) {
    d3.select(this).attr("cx", d.x = d3.event.x).attr("cy", d.y = d3.event.y);
}).on("end", function(d) {
    console.log("x distance: " + (d.x - d.startX))
    console.log("y distance: " + (d.y - d.startY))
})

, :

var svg = d3.select("svg");
var circle = svg.append("circle")
  .datum({
    x: 150,
    y: 75
  })
  .attr("cx", function(d) {
    return d.x
  })
  .attr("cy", function(d) {
    return d.y
  })
  .attr("r", 10)
  .attr("fill", "teal");

circle.call(d3.drag().on("start", function(d) {
  d.startX = d.x;
  d.startY = d.y;
}).on("drag", function(d) {
  d3.select(this).attr("cx", d.x = d3.event.x).attr("cy", d.y = d3.event.y);
}).on("end", function(d) {
  console.log("x distance: " + (d.x - d.startX))
  console.log("y distance: " + (d.y - d.startY))
}))
svg {
  border: 1px solid black;
}

.as-console-wrapper { max-height: 25% !important;}
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg></svg>
Hide result

: , " ", , , , , .

+2

Source: https://habr.com/ru/post/1684004/


All Articles