Last active
April 27, 2024 17:31
-
-
Save R-ohit-B-isht/d618a8f288f55f4b16866bbd66501a56 to your computer and use it in GitHub Desktop.
This file contains 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
function convertDivToImage(divSelector) { | |
// Get the div element by CSS selector | |
let div = document.querySelectorAll(divSelector); | |
// Check if the div element exists | |
if (!div) { | |
div = document.getElementById(divSelector); | |
if (!div){ | |
console.error(`No element found`); | |
return; | |
} | |
} | |
// Use html2canvas to capture the div as a canvas | |
html2canvas(div).then(function(canvas) { | |
// Convert the canvas to a data URL | |
const imageDataURL = canvas.toDataURL('image/png'); | |
// Create a temporary anchor element | |
const downloadLink = document.createElement('a'); | |
downloadLink.setAttribute('href', imageDataURL); | |
downloadLink.setAttribute('download', 'captured_div.png'); | |
// Programmatically trigger the download | |
downloadLink.click(); | |
console.log(`Image captured for div with selector: ${divSelector}`); | |
}).catch(function(error) { | |
console.error('Error capturing div as image:', error); | |
}); | |
} | |
// Usage example | |
convertDivToImage('<divID> or .<classname>'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment