Drag and swap Sag objects JS

Viewed 37

I'm making a dragging function for an SVG in which I can drag one of the sag objects anywhere in the container.

I need to drag the blue rectangle infant on the grey rectangle and when I left the key of the button they should swap places, making the grey rectangle go to where the blue one started when I left click on it and the blue rectangle stays where the gray one left off.

I don't know how to proceed with this swap function

function makeDraggable(evt) {

  var svg = evt.target;
  var selectedElement, offset;
  svg.addEventListener('mousedown', startDrag);
  svg.addEventListener('mousemove', drag);
  svg.addEventListener('mouseup', endDrag);
  svg.addEventListener('mouseleave', endDrag);

  function startDrag(evt) {
    if (evt.target.classList.contains('draggable')) {
      selectedElement = evt.target;
      offset = getMousePosition(evt);
      offset.x -= parseFloat(selectedElement.getAttributeNS(null, "x"));
      offset.y -= parseFloat(selectedElement.getAttributeNS(null, "y"));
    }
  }

  function drag(evt) {
    if (selectedElement) {
      evt.preventDefault();
      var coord = getMousePosition(evt);
      selectedElement.setAttributeNS(null, "x", coord.x - offset.x);
      selectedElement.setAttributeNS(null, "y", coord.y - offset.y);
    }
  }

  function endDrag(evt) {
    selectedElement = null;

  }

  function getMousePosition(evt) {
    var CTM = svg.getScreenCTM();
    return {
      x: (evt.clientX - CTM.e) / CTM.a,
      y: (evt.clientY - CTM.f) / CTM.d
    };
  }

}
.draggable {
  cursor: move;
}
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 30 20" onload="makeDraggable(evt)">
  <rect x="0" y="0" width="30" height="20" fill="#fafafa" />
  <rect x="4" y="5" width="8" height="10" fill="#007bff" /> 
  <rect x="18" y="5" width="8" height="10"   fill="#888" />
</svg>

enter image description here

0 Answers
Related