Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save R-ohit-B-isht/d618a8f288f55f4b16866bbd66501a56 to your computer and use it in GitHub Desktop.
Save R-ohit-B-isht/d618a8f288f55f4b16866bbd66501a56 to your computer and use it in GitHub Desktop.
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