将画布下载为PNG图像

Download a canvas as PNG image

本文关键字:PNG 图像 下载 布下载      更新时间:2023-09-26

当我尝试将画布下载为PNG图像时,浏览器会在新页面中打开图像,但不会下载。。。我的下载代码:

$("#btnScaricaEtichetta").click(function(){
    console.log("Download... ");
    location.href = document.getElementById("latoSinistro").toDataURL();
    this.download = "filename";
});

有没有办法简单地下载它?抱歉英语不好,我是意大利人

因为它使用外部函数,这有点像黑客攻击,但它似乎在任何浏览器上都能工作。我使用工具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>