Why does the d3.js group element jump on the first drag?

I need to create a d3 group with some shapes (e.g. rect, circle, ...) in it, and I need to drag it. Drag and Drop works, but when the drag starts, the form “jumps”. I know I need something like .attr("x", d.x = d3.event.x). But then I get an error that "d" is undefined. How can I fix a jump? Here is a very simple code:

var svg = d3.select("body").append("svg")
.attr("preserveAspectRatio", "xMinYMin meet")
.attr("viewBox", "0 0 960 600")
.attr("width", "100%")
.attr("height", "100%");

rectGroup();

function rectGroup() {
var group = svg.append('g')
    .attr("class", "group")
    .call(d3.drag()
        .on("drag", dragged));

group.append("rect")
    .data([{ x: 200, y: 200, width: 100 , height: 100}])
    .attr('class', 'rect')
    .attr("x", function(d) { return d.x; })
    .attr('y', function(d) { return d.y; })
    .attr('width', function(d) { return d.width; })
    .attr('height', function(d) { return d.height; });
}

function dragged(d) {
d3.select(this).select("rect").attr("x", d3.event.x)
d3.select(this).select("rect").attr("y", d3.event.y)
}
+4
source share
1 answer

You call dragin groups. However, you use properties xand yfor rectangles in the function dragged.

, drag , , .

, , translate:

function dragged(d) {
    d3.select(this).attr("transform", "translate(" + (d.x = d3.event.x) + 
    "," + (d.y = d3.event.y) + ")")
}

x y .

:

var svg = d3.select("body").append("svg")
  .attr("preserveAspectRatio", "xMinYMin meet")
  .attr("viewBox", "0 0 960 600")
  .attr("width", "100%")
  .attr("height", "100%");

rectGroup();

function rectGroup() {
  var group = svg.append('g')
    .datum({
      x: 0,
      y: 0
    })
    .attr("class", "group")
    .call(d3.drag()
      .on("drag", dragged));

  group.append("rect")
    .data([{
      x: 200,
      y: 200,
      width: 100,
      height: 100
    }])
    .attr('class', 'rect')
    .attr("x", function(d) {
      return d.x;
    })
    .attr('y', function(d) {
      return d.y;
    })
    .attr('width', function(d) {
      return d.width;
    })
    .attr('height', function(d) {
      return d.height;
    });
}

function dragged(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>
Hide result
+2

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


All Articles