[英]Download html2canvas image to desktop
我找到了這個https://jsfiddle.net/8ypxW/3/ ,我想知道如何將圖像下載到桌面。 我只看到保存 png 但如果可能的話沒有下載你能給我腳本嗎?
$(function() {
$("#btnSave").click(function() {
html2canvas($("#widget"), {
onrendered: function(canvas) {
theCanvas = canvas;
document.body.appendChild(canvas);
// Convert and download as image
Canvas2Image.saveAsPNG(canvas);
$("#img-out").append(canvas);
// Clean up
//document.body.removeChild(canvas);
}
});
});
});
問題是您的小提琴中 canvas2image.js 腳本的 URL 錯誤。 我用合適的小提琴制作了一個小提琴讓你看看。 在下面的代碼中,您可以看到 2 個“保存 PNG”按鈕。 一種是使用 Canvas2Image.saveAsPNG 函數,但這種方法的一個小問題是您無法給出保存圖像的名稱。 第二個按鈕使用HTML 下載屬性,但並非所有瀏覽器都支持。
$(function() {
$("#btnSave").click(function() {
html2canvas($("#widget"), {
onrendered: function(canvas) {
Canvas2Image.saveAsPNG(canvas);
}
});
});
$("#btnSave2").click(function() {
html2canvas($("#widget"), {
onrendered: function(canvas) {
saveAs(canvas.toDataURL(), 'canvas.png');
}
});
});
function saveAs(uri, filename) {
var link = document.createElement('a');
if (typeof link.download === 'string') {
link.href = uri;
link.download = filename;
//Firefox requires the link to be in the body
document.body.appendChild(link);
//simulate click
link.click();
//remove the link when done
document.body.removeChild(link);
} else {
window.open(uri);
}
}
});
為了能夠將圖像下載到用戶計算機,您可以使用以下方法:
<html>
<head></head>
<body>
<div id="boundary">
<div class="content">
<p>My content here</p>
</div>
</div>
<button id="download">Download</button>
</body>
</html>
基於Krzysztof 的回答
document.getElementById("download").addEventListener("click", function() {
html2canvas(document.querySelector('#boundary')).then(function(canvas) {
console.log(canvas);
saveAs(canvas.toDataURL(), 'file-name.png');
});
});
function saveAs(uri, filename) {
var link = document.createElement('a');
if (typeof link.download === 'string') {
link.href = uri;
link.download = filename;
//Firefox requires the link to be in the body
document.body.appendChild(link);
//simulate click
link.click();
//remove the link when done
document.body.removeChild(link);
} else {
window.open(uri);
}
}
事實上,我能夠下載圖像,但它是空白的......可能的原因(至少在我的情況下)是內容包裝器( id="#boundary" )沒有定義寬度或高度,因此指定內容包裝器的高度和寬度對我有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.