1

I am trying to drag and drop a logo into 2 SVG circles. From the help of my code, the image is being dragged into one circle ,but it's not getting dragged to another circle.

How to modify the code so that the image can be dragged/dropped between 2 circles?

function drag(ev) {
     ev.dataTransfer.setData("text", ev.target.id);
  }

  function allow(ev){
   ev.preventDefault();
  }

  function drop(ev) {
     ev.preventDefault();
     var data = ev.dataTransfer.getData("text");
     var img1=document.getElementById(data),
         imgSrc=img1.getAttribute('src'),
         imgw=img1.getAttribute('width')
         imgh=img1.getAttribute('height'),
         imgX = ev.target.getAttribute('cx') - ev.target.getAttribute('r')+20;
         console.log(imgX);
         ev.target.parentElement.innerHTML += '<image xlink:href="' + imgSrc + '" x="' + imgX + '" y="0" width="' + imgw + 'px" height="' + imgh + 'px"/>';
         img1.parentNode.removeChild(img1);

     //ev.target.appendChild(document.getElementById(data));
  }
<!DOCTYPE html>
<html>
<head>
 <title>Assignment1_HTML_L2</title>
 
</head>
<body>
   <div id="circle" ondrop="drop(event)" ondragover="allow(event)" >
 <svg width="1000" height="200">
    <circle id="c1" cx="70" cy="50" r="50" stroke="green" fill="white" stroke-width="4"  style="opacity: 1;" /> 

    <circle cx="200" cy="50" r="50" stroke="yellow"  fill="white" stroke-width="4"  style="opacity: 1;"/>
   </svg>
  </div>
  <image id="p1" src="https://media.giphy.com/media/l3vR16pONsV8cKkWk/giphy.gif" alt="picture" draggable="true" ondragstart="drag(event)" width="30" height="30" style="opacity: 1;">

</body>
</html>

UPDATE :

Posted the link of SVG file in the answer section !!

teddcp
  • 1,514
  • 2
  • 11
  • 25

2 Answers2

0

The HTML draggable/ondragstartetc are HTML attributes. They don't work in SVGs. So you'll need to implement the dragging using standard mouse events.

See: Drag and drop events in embedded SVG?

And thre are many other questions on S.O. related to implementing dragging in SVGs.

Paul LeBeau
  • 97,474
  • 9
  • 154
  • 181
0

With the help of Paul, i found the answer. Make sure that the file extension should be in svg. Also you can include it in html.

File Link

teddcp
  • 1,514
  • 2
  • 11
  • 25