Reputation: 1
I want to Drag a image into a SVG circle. While debugging image is available as a child but it's not showing on circle. When I dragging the same image into a <div>
element it's working fine but not for <SVG>
or <Image>
tag. With <div>
it's working fine but not with <IMAGE>
.
Q . Draw a circles of color yellow and green using SVG and allow users to drag and drop a logo into the circles .
https://www.w3schools.com/code/tryit.asp?filename=FVF69MCUNTQ0
Upvotes: 0
Views: 6420
Reputation: 71
You can not use drag events in SVGs but there is a trick. You can have two sections (one overlaying the other) by setting the z-index property on one of the sections. Have a look at below code :
CSS :
#container{
text-align: center;
margin: -20px 20% 0 20%;
background: #b9cae5;
}
#SVGs{
width:100px;
height:100px;
margin: 20px 0 0 350px;
position:relative;
}
.sec1,.sec2{
width:100px;
height:100px;
position:absolute;
top:0;
left:0;
}
.sec1{
z-index:10;
}
in your HTML :
<section id ="container">
<section id="SVGs">
<section class="sec2">
<svg width="100" height="100">
<circle id="abc" cx="50" cy="50" r="50" stroke="black" fill="yellow">
</circle>
</svg>
</section>
<section id="sec1"class="sec1" ondrop="drop(event)" ondragover="allowDrop(event)">
</section>
<br/><br/>
</section>
<section>
<p> <strong>Drag the gif image to the SVG circles above.</strong>
</p>
<img id="drg1" alt="Check Internet Connection"src="https://media.giphy.com/media/l3vR16pONsV8cKkWk/giphy.gif" draggable="true" ondragstart="drag(event)" width="100" height="100"/>
</section>
and your script :
<script>
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
ev.dataTransfer.setData("text", ev.target.id);
}
function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("text");
ev.target.appendChild(document.getElementById(data));
}
</script>
I hope it helps :)
Upvotes: 2