Screenshot DOM using JS
If you want to take screenshot of your website using JS, html2canvas
is the goto library. But for some reason it did not work for me when I was trying it to get a screenshot of a map rendered using leaflet.js
.
I found html-to-image
to be a more reliable library for taking screenshots.
Using html-to-image
is very simple. The docs are self sufficient. My use case was to upload the image blob to the backend and here’s what I did.
import * as htmlToImage from "html-to-image";
htmlToImage.toBlob(document.getElementById("map")).then(function (blob) {
const formdata = new FormData();
formdata.append("image", blob, "image.png");
formdata.append("file_id", fileId);
axios.post("/api/report", formdata, { responseType: "blob" }).then((res) => {
console.log(res.data);
});
});