I have a div consisting of two divs. div1 has a yellow background and a black border and under it is div2 containing an image.
I want to drag and drop that image into div1 and save all of it as a png.
The problem is that the saved image contains only the content of div1 without the dropped image. I want to save the content of div1 with the image also.
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");
var parent = ev.target.parentNode;
ev.target.appendChild(document.getElementById(data));
}
$(document).ready(function() {
var element = $("#contentImage"); // global variable
var getCanvas; //global variable
html2canvas(element, {
onrendered: function(canvas) {
getCanvas = canvas;
}
});
$("#saveAsPNG").on('click', function() {
var imgageData = getCanvas.toDataURL("image/png");
var newData = imgageData.replace(/^data:image\/png/, "data:application/octet-stream");
$("#convertToPNG").attr("download", "your_image.png").attr("href", newData);
});
});
.div {
width: 200px;
height: 400px;
}
.div1 {
width: 200px;
height: 200px;
background-color: yellow;
border-style: solid;
border-color: black;
}
.div2 {
width: 200px;
height: 200px;
}
.image1 {
display: block;
margin-left: auto;
margin-right: auto;
}
<!DOCTYPE HTML>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>
</head>
<body>
<div class="div">
<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>
<br><br>
<a id="saveAsPNG" href="#">convert to image</a>
</div>
</body>
</html>