I want to convert a div to canvas and then eventually to image. So I am using the html2canvas library. I have tried downloading image, opening image in new window, and appending to a div, but none of them has worked.
$(document).ready(function (e) {
$("#final_download").click(function() {
html2canvas($("#final_image_div")[0]).then(function (canvas) {
console.log(canvas);
var myImage = canvas.toDataURL("image/png");
// download the generated image
downloadURI(myImage, "final_image.png");
// Open the image in a new window
window.open(myImage , "_blank");
// display it in div
$("#bottom").append(myImage);
});
});
});
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.3.3/html2canvas.min.js"></script>
<div id="final_image_div">abcdef</div>
<img src="images/download.jpg" id="final_download">
<div class="bottom"></div>
Any idea as to what I am doing wrong here?
I tried to run your code and it was just lacking a dowloadURL function (there is no such thing in Vanilla JS).
I simply added the following code and then everything worked as expected :
function downloadURI(uri, name) {
var link = document.createElement("a");
link.download = name;
link.href = uri;
link.click();
}
FYI I found this function here