I want to take a screenshot of an element in the DOM using javascript and save it on my local computer automatically without phyically clicking on a button. I have seen many suggestion but none is really working the way I want it. This are some of the examples I read. example1, example 2
<!DOCTYPE html>
<html>
<body>
<script src="jquery-3.2.1.min.js"></script>
<p>This is some text.</p>
<div style="color:#0000FF" id="myContainer" >
<h3>This is a heading in a div element</h3>
<p>This is some text in a div element.</p>
</div>
<p>This is some text.</p>
<script type="text/javascript">
try {
debugger;
$.getScript("html2canvas.js", function() {
var takeScreenShot = function() {
html2canvas($("#myContainer"), {
onrendered: function (canvas) {
var tempcanvas=document.createElement("canvas");
tempcanvas.width=350;
tempcanvas.height=350;
var context=tempcanvas.getContext("2d");
context.drawImage(canvas,112,0,288,200,0,0,350,350);
var link=document.createElement("a");
link.href=tempcanvas.toDataURL("image/png")
link.download = "myImage.png";
link.click();
}
});
} });
}
catch (err) {
alert(err.message);
}
</script>
</body>
</html>
The problem is that I am getting no error and I am having no screenshot.
You are defining the function takeScreenShot, but never actually call it. You need to call the function with takeScreenShot();
or more complete:
try {
debugger;
$.getScript("html2canvas.js", function() {
var takeScreenShot = function() {
html2canvas($("#myContainer"), {
onrendered: function (canvas) {
var tempcanvas=document.createElement("canvas");
tempcanvas.width=350;
tempcanvas.height=350;
var context=tempcanvas.getContext("2d");
context.drawImage(canvas,112,0,288,200,0,0,350,350);
var link=document.createElement("a");
link.href=tempcanvas.toDataURL("image/png")
link.download = "myImage.png";
link.click();
}
});
}
takeScreenShot();
});
}
catch (err) {
alert(err.message);
}