Created
December 19, 2021 09:36
-
-
Save karnpapon/20de03d8d042c4699a2dc03f097ca8e7 to your computer and use it in GitHub Desktop.
download div element as image via DevTools.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 1. create script element and append to head; | |
const sc = document.createElement("script"); | |
sc.setAttribute("src", "https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"); | |
document.head.append(sc) | |
// 2.create downloader function | |
function downloadBase64File(contentType, base64Data, fileName) { | |
const linkSource = `data:${contentType};base64,${base64Data}`; | |
const downloadLink = document.createElement("a"); | |
downloadLink.href = linkSource; | |
downloadLink.download = fileName; | |
downloadLink.click(); | |
} | |
// 3.executed as an IIFE. (needs an target id as param) | |
(function getScreenShot(id){ | |
let c = document.getElementById(id); | |
let h = html2canvas(c, { | |
onrendered: function(canvas) { | |
let t = canvas.toDataURL().replace("data:image/png;base64,", ""); | |
downloadBase64File('image/png',t,'image'); | |
} | |
})} | |
)("div_print"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment