I have only a button and an image inside the "rightcontainer" div. When I click on the button, it should take a screenshot to the div. It does but the image is not showing only the words. I read about that, and I think because the image is not in the div DOM. How can I make the image part of the div so that it appears in the screenshot as well.
$(".drag").draggable();
$(".drag").droppable();
var takeScreenShot = function() {
html2canvas(document.getElementById("container"), {
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/jpg'); //function blocks CORS
link.download = 'screenshot.jpg';
link.click();
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>
<button onclick="takeScreenShot()">Snapshot</button>
<div id="container">
<div id="leftmenu">
Left Side
<div class="drag">
</div>
<div class="drag">
</div>
<div class="drag">
</div>
Drag----------->
&
Click Snapppppppppppppp </br>
</div>
<div id="rightcontainer">
Right Side
<img id = "conn" src="https://static.pexels.com/photos/39803/pexels-photo-39803.jpeg" width="500px" ;>
</div>
</div>
The problem here is that the image is coming from an external website. html2canvas will only process images that come from the same origin as the HTML file, i.e. the same web domain.
A potential workaround to this issue would be to use some kind of proxy, but the best solution is probably to just download the image and serve it along with your website.
You can read more on html2canvas's documentation website (this issue is listed under the "Limitations" section), and if you are interested in using a proxy to resolve this matter, they are discussed here.
Secondly, you're using an old version of html2canvas. Download the latest version, and then replace your takeScreenShot
function with this version (as the new API uses promises, rather than callbacks):
var takeScreenShot = function() {
html2canvas(document.getElementById("container")).then(canvas=>{
var link = document.createElement("a");
link.href = canvas.toDataURL('image/jpg');
link.download = 'screenshot.jpg';
link.click();
})
}
This will create the correct output (you can test by doing document.body.appendChild(canvas)
before the var link
line), but you won't be able to download it, as the canvas will be "tainted". To fix this, you'll have to run the site off some kind of local server (if you're not already), for example XAMPP.