Monday, 26 April 2021

Drag a rect and append to a respective group

I am trying to drag the lime rectangle and append to a respective group that i dropped.

I have multiple groups, because that i can't use the <g> reference directly. I don't know if i need to clone or i can use the same rectangle.

But, i can't know who is the target of the drop, because the rectangle first group always change the size.

So for an example:

<svg id="graph" height="310" width="600" style="border: 1px solid #000;"></svg>

<!-- scripts -->
<script src="//d3js.org/d3.v4.min.js"></script>
<script>

    /* create svg & container */
  var svg = d3.select('svg').attr('focusable', false);
  var container = svg.append('g').attr('id', 'container');
  var use = svg.append('use').attr('xlink:href', '#action');
  
  /* create groups */
  var groupOne = container.append('g').attr('class', 'group').attr('transform', 'matrix(1,0,0,1, 0, 0)');
  var groupTwo = container.append('g').attr('class', 'group').attr('y', 160).attr('transform', 'matrix(1,0,0,1, 0, 160)');
  var groupThree = container.append('g').attr('class', 'group').attr('y', 160).attr('transform', 'matrix(1,0,0,1, 170, 0)');
  
  
  /* create group content  */
  var bgGroupOne = groupOne.append('rect')
    .attr('height', '150')
    .attr('width', '150')
    .attr('fill', 'red');
    
  var txtGroupOne = groupOne.append('text')
    .attr('y', 20)
    .attr('x', 10)
    .attr('font-size', "12")
    .attr('fill', "#FFF")
    .text('Group 1');
    
    var bgGroupTwo = groupTwo.append('rect')
    .attr('height', '150')
    .attr('width', '150')
    .attr('fill', 'blue');
    
 var txtGroupTwo = groupTwo.append('text')
    .attr('y', 20)
    .attr('x', 10)
    .attr('font-size', "12")
    .attr('fill', "#FFF")
    .text('Group 2');
  
  var bgGroupThree = groupThree.append('rect')
    .attr('height', '150')
    .attr('width', '150')
    .attr('fill', 'violet');
    
 var txtGroupThree = groupThree.append('text')
    .attr('y', 20)
    .attr('x', 10)
    .attr('font-size', "12")
    .attr('fill', "#FFF")
    .text('Group 3');
    
  
  var draggableElement = groupOne.append('rect')
    .attr('height', 70)
    .attr('width', 70)
    .attr('x', 40)
    .attr('y', 70)
    .attr('stroke', 'black')
    .attr('stroke-width', 2)
    .attr('fill', 'lime')
    .attr('cursor', 'move')
    .attr('id', 'action')
    .call(
        d3.drag()
        .on('start', onDragStart)
        .on('drag', onDragged)
        .on('end', onDragEnd)
    );
  
  
  /* drag functions */
  function onDragStart() {
    d3.select(this).classed("active", true);
  }
  
  function onDragged(d) {
    return d3.select(this).attr('x', d3.event.x).attr('y', d3.event.y);
  }

  function onDragEnd() {
    
  }
  
  
</script>


from Drag a rect and append to a respective group

No comments:

Post a Comment