Screenshot of a specific part of the screen using html5
Hello, dear friends. There is such a task: Turn the contents of the div block into an image and invite the user to download it.
<!DOCTYPE html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<style type="text/css">
div {
width:200px;
background-color: green;
}
</style>
<script type="text/javascript" src="http://night-creature.com/html2canvas.js"></script>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
</head>
<body>
<div id="downimg">
<div>
some text
</div>
</div>
<script language="javascript">
function downimg(){
html2canvas($('#downimg'), {
onrendered: function (canvas) {
var img = canvas.toDataURL('image/png').replace("image/png", "image/octet-stream");
window.location.href = img;
}
});
}
</script>
<a href="javascript:void(0)" onClick="downimg()" >SAVE</a>
</body>
</html>
It would seem that the problem is solved. But, the image is downloaded without an extension and even without a name. Is there any way, without involving server technologies, to give a name to the screenshot?
4 answers
Http://htmlbook.ru/html/a/download
in version 5, a magic attribute is added, but I think not all browsers will pull it
<a download="img.png" href="javascript:void(0)" onClick="downimg()" >SAVE</a>
It seems that you can't do without a small server code after all. Using javascript, we can't change the Content-disposition header, and it's the one that sets the browser's behavior - display or save. Still, you will have to add a dozen lines (here is the PHP example) to get the desired behavior.
There is an alternative - save with a flash drive. The server is not needed.
See, your image is generated on the fly and translated to base64
. Accordingly, you get in toDataURL()
not a picture, but only a set of characters.