I want to make a JS function which can take the screenshot from element and then download it.
<body> <h1>Sample text</h1> <h2>Sample text</h2> <table width="1080px" height="1920px" border="1" style="border-collapse:collapse"> <tbody><tr> <td colspan="2"> <img src="https://inspectiondoc.com/wp-content/uploads/2014/08/sample-icon.png" width="600px"> </td> <td> Sample text </td> </tr> <tr style="background:#b6ff00"> <td> Sample text </td> <td> Sample text </td> <td> Sample text </td> </tr> </tbody></table> <h1> sample text </h1> <h2>Sample text</h2> <br><br> <input type="button" value="Capture" onclick="capture()"> </body>
After clicking capture button I want this td colspan="2" element to be screenshoted and downloaded on jpg or png format.
Using html2canvas could help you, it converts an element into a canvas, and then you just need to add its data as a url into an a element
function download(canvas, filename) {
const data = canvas.toDataURL("image/png;base64");
const donwloadLink = document.querySelector("#download");
donwloadLink.download = filename;
donwloadLink.href = data;
}
html2canvas(document.querySelector(".card")).then((canvas) => {
// document.body.appendChild(canvas);
download(canvas, "asd");
});
Check a full example here https://codepen.io/koseare/pen/NWpMjeP
Try with html2canvas
;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div id="all">
<h2>Sample text</h2>
<table width="1080px" height="1920px" style="border-collapse: collapse">
<tbody>
<tr>
<td colspan="2">
<img
src="https://inspectiondoc.com/wp-content/uploads/2014/08/sample-icon.png"
width="600px"
/>
</td>
<td>Sample text</td>
</tr>
<tr style="background: #b6ff00">
<td>Sample text</td>
<td>Sample text</td>
<td>Sample text</td>
</tr>
</tbody>
</table>
</div>
<br />
<input type="button" id="btn" value="Download" />
<script>
document.getElementById("btn").addEventListener(
"click",
function () {
var text = document.getElementById("all").value;
var filename = "output.txt";
download(filename, function makeScreenshot() {
html2canvas(document.getElementById("screenshot"), {scale: 1}).then(canvas => {
document.body.appendChild(canvas);
});
});
},
false
);
</script>
</body>
</html>
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.