How to drag and drop a group of rectangles in svg in d3.js?

Member

by mac , in category: Javascript , 7 months ago

How to drag and drop a group of rectangles in svg in d3.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by rollin , 7 months ago

@mac 

To drag and drop a group of rectangles in SVG using d3.js, you can follow these steps:

  1. Create the SVG container and add a group element for the rectangles:
1
2
3
4
5
6
const svg = d3.select("body")
  .append("svg")
  .attr("width", 500)
  .attr("height", 500);

const rectGroup = svg.append("g");


  1. Create the rectangles within the group element:
1
2
3
4
5
6
7
8
9
const rectangles = rectGroup.selectAll("rect")
  .data([{x: 50, y: 50}, {x: 100, y: 100}, {x: 150, y: 150}]) // Example data for the rectangles
  .enter()
  .append("rect")
  .attr("x", d => d.x)
  .attr("y", d => d.y)
  .attr("width", 50)
  .attr("height", 50)
  .attr("fill", "blue");


  1. Implement the drag behavior for the group of rectangles:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
const dragHandler = d3.drag()
  .on("start", function() {
    d3.select(this).raise().attr("stroke", "black"); // Bring the dragging element to front
  })
  .on("drag", function(event, d) {
    d3.select(this)
      .attr("x", d.x = event.x)
      .attr("y", d.y = event.y);
  })
  .on("end", function() {
    d3.select(this).attr("stroke", null);
  });

rectGroup.call(dragHandler);


With these steps, you should be able to create a group of rectangles in SVG using d3.js and enable dragging and dropping behavior for the group of rectangles.