当我尝试将我的 Canvas 下载为 PNG 图像时,浏览器会在新页面中打开图像,但不会下载它...
我的下载代码:
$("#btnScaricaEtichetta").click(function(){
console.log("Download... ");
location.href = document.getElementById("latoSinistro").toDataURL();
this.download = "filename";
});
有没有简单下载的方法呢?
抱歉英语不好,我是意大利人
因为它使用外部函数,这有点像 hack,但它似乎在任何浏览器上都有效。我正在使用 FileSaver.js 工具执行文件下载工作,并使用 canvas-toBlob.js 在 Chrome 和其他浏览器上执行 toBlob 功能。
<script src="https://rawgit.com/eligrey/FileSaver.js/master/FileSaver.js"></script>
<script src ="https://rawgit.com/eligrey/canvas-toBlob.js/master/canvas-toBlob.js"></script>
<h1 onclick="download_image()">Click Here to download image</h1>
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;">
<script>
// lets put something on a canvas..
// reminder this works without jQuery .ready() only because this script is the last element in the document.
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "#FF0000";
ctx.fillRect(0,0,150,75);
ctx.moveTo(0,0);
ctx.lineTo(200,100);
ctx.stroke();
ctx.beginPath();
ctx.arc(95,50,40,0,2*Math.PI);
ctx.stroke();
function download_image(){
// Dump the canvas contents to a file.
var canvas = document.getElementById("myCanvas");
canvas.toBlob(function(blob) {
saveAs(blob, "output.png");
}, "image/png");
};
</script>