0

I have a .div1 and .div2. .div2 contains an image.

I want to drag and drop image from .div2 to .div1 and save the content of .div1 as png.

The problem is that I always have to click twice on the "convert to image" button.

I want to do it only once.

This is my code so far

function allowDrop(ev) {
        ev.preventDefault();
    }
 
    function dragStart(ev) {
        ev.dataTransfer.setData("text", ev.target.id);
    }
 
    function dragDrop(ev) {
        ev.preventDefault();
        var data = ev.dataTransfer.getData("text");
        ev.target.appendChild(document.getElementById(data));

    $(document).ready(function() {
       $("#convertToImage").on('click', function() {
            let element = $("#contentImage");
            html2canvas(element, {
                  onrendered: function(canvas) {
                  getCanvas = canvas;
                  }
             });

            var imgageData = getCanvas.toDataURL("image/png");
            var newData = imgageData.replace(/^data:image\/png/, "data:application/octet-stream");
            $("#convertToImage").attr("download", "your_image.png").attr("href", newData);

         });

    });
    }
.div1 {
  width: 200px;
  height: 100px;
  background-color: orange;
  border: solid 2px black;
}

.div2 {
  width: 200px;
  height: 100px;
  background-color: blue;
  border: solid 2px black;
}

.image1 {
  width: 50px;
  height: 50px;
  margin: auto;
  display: block;
  background-color: black;
  border: solid 2px black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="div1" ondrop="dragDrop(event)" ondragover="allowDrop(event)" id="contentImage">
</div>
<div class="div2" draggable="true" ondragstart="dragStart(event)">
    <img id="img2" class="image1" src="/path/to/image" draggable="true" ondragstart="dragStart(event)" width="160" height="160">
 </div>
 <a id="btn-Convert-Html2Image" href="#">convert to image</a>
GreyRoofPigeon
  • 17,833
  • 4
  • 36
  • 59
chessrealm
  • 13
  • 4

0 Answers0