This is the code which I am using to convert div into image and download that using html2canvas.js
Here is a simple way to do this.
You will get a image downloaded.
Here is a demo: this JSFiddle.
In this fiddle, two libraries are used:
dom-to-image
: https://github.com/tsayen/dom-to-image
FileSaver.js
: https://github.com/eligrey/FileSaver.js/
First one is used to turn dom into image, second one is used to download the image.
Update: If you want to get a img of base64 instead of just downloading img as the blob format. You can do as below:
domToImage
.toBlob(document.getElementById("my-node"))
.then(function(blob) {
saveBlobAsFile(blob, "XX.png");
});
// this function is to convert blob to base64 img
function saveBlobAsFile(blob, fileName) {
var reader = new FileReader();
reader.onloadend = function() {
var base64 = reader.result;
var img = document.createElement("img");
img.classList.add("me-img");
img.setAttribute("src", base64);
// insert the img to dom
document.getElementById("bar").appendChild(img);
};
reader.readAsDataURL(blob);
}
Here FileSaver.js
is not needed, we use html5 api FileReader to do the trick.