Capture and Download HTML with JavaScript
It comes in handy if we can capture certain areas from your site and download them as images, isn’t cool? that’s cool of course.
Our first step would be to convert HTML areas to canvas.
With this, we can use third-party lib e.g. html2canvas created by Niklas von Hertzen.
html2canvas(document.querySelector("#capture")).then(canvas => {
// do something from the returned canvas
});
Keep in mind that if you plan to capture canvas
an already HTML section from your site, there’s no need to use third-party lib, like I’ve mentioned above, instead, we can fully utilize the built-in JavaScript method.
HTMLCanvasElement.toDataURL()
const canvas = document.getElementById('canvas');
const dataURL = canvas.toDataURL();
console.log(dataURL);
The above code returned the image in base64
format, you can play more like setting the quality and more, refer to the site reference below.
Now back to the real thing, capturing certain areas from your site and downloading it as an image, yes.
Full source code
html2canvas(document.querySelector('#capture')).then(canvas => {
// convert canvas to base64, but this time we get the binary form, thus replacin the image MIME type to octet-stream
const dataURL = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream")
// yeh, a dirty tricks to download our image above, that's it
let a = document.createElement('a');
a.href = dataURL;
a.download = "download.png"; // your file-name
document.body.appendChild(a);
a.click();
});
and that’s it, happy coding ^_^
References and Credits
HTML to Canvas
https://html2canvas.hertzen.com/
HTMLCanvasElement
https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toDataURL