我正在使用HTML2canvas .4.1渲染onclick的屏幕快照,并希望将图像保存到用户的本地计算机。如何做到这一点?请注意,我是一个初学者,因此实际代码对我最有帮助。
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript" src="html2canvas.js"></script>
<button id="save_image_locally">download img</button>
<div id="imagesave">
<img id='local_image' src='img1.jpg'>
</div>
<script>
$('#save_image_locally').click(function(){
html2canvas($('#imagesave'),
{
onrendered: function (canvas) {
var img = canvas.toDataURL("image/png");
alert('This will currently open image in a new window called "data:". Instead I want to save to users local computer. Ideally as a jpg instead of png.');
window.open(img);
}
});
});
</script>
注意:此答案来自2015年,并且库已更新。
请查看以下答案,以了解其他实现方式。
尝试此操作(请注意,它利用了download属性。有关支持download属性的浏览器,请参见caniuse支持表)
<script>
$('#save_image_locally').click(function(){
html2canvas($('#imagesave'),
{
onrendered: function (canvas) {
var a = document.createElement('a');
// toDataURL defaults to png, so we need to request a jpeg, then convert for file download.
a.href = canvas.toDataURL("image/jpeg").replace("image/jpeg", "image/octet-stream");
a.download = 'somefilename.jpg';
a.click();
}
});
});
</script>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句