I am trying to save and download div
content as an image. I resorted to this solution which suggests using html2canvas
.
I have implemented the code below but cannot get the div
content to be saved and downloaded as an image. How can I do this in jQuery or JavaScript?
Here is my code so far:
<!doctype html>
<html>
<head>
<script type="text/javascript" src="html2canvas-master/dist/html2canvas.js"></script>
</head>
<body>
<h1> Div Data to be Save and Download</h1>
<div class="div1" id='div1'>
<h2> Iam Div1</h2>
<img src='images/div1_image.jpg' width='100' height='100'>
</div><br/>
<input type='button' id='but_screenshot' value='Download as Image' onclick='download();'><br/><br/>
<!-- Script -->
<script type='text/javascript'>
function download() {
// html2canvas(document.body).then(function(canvas) {
html2canvas(document.getElementById('div1')).then(function(canvas) {
document.body.appendChild(canvas);
});
}
</script>
</body>
</html>
Extend your download()
function with the next code:
function download() {
html2canvas(document.getElementById("div1")).then(function(canvas) {
document.body.appendChild(canvas);
const image = canvas.toDataURL("image/png", 1.0);
const link = document.createElement("a");
link.download = "my-image.png";
link.href = image;
link.click();
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.