【问题标题】:Download a canvas as PNG image [duplicate]将画布下载为PNG图像[重复]
【发布时间】:2016-08-27 10:57:15
【问题描述】:

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

$("#btnScaricaEtichetta").click(function(){
    console.log("Download... ");

    location.href = document.getElementById("latoSinistro").toDataURL();
    this.download = "filename";
});

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

【问题讨论】:

  • canvas.toDataURL("image/png") ?你确定location.href 正确地抓住了画布吗?另请查看image/png 参数。
  • 我已将“image/png”添加到 toDataURL 函数,但结果没有改变......浏览器打开一个窗口并显示带有此 url 的 img:data:image/png;base64 ,iVBORw0KGgoA ecc ecc (这么久)
  • this.download = "filename"; 行中,不清楚this 指向什么。
  • @Kaiido ...只是想法...这些只是想法。 :-P

标签: javascript html canvas download png


【解决方案1】:

因为它使用外部函数,所以这有点像 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>

【讨论】:

  • 工作,非常感谢(:
猜你喜欢
  • 2017-06-22
  • 1970-01-01
  • 1970-01-01
  • 2023-03-18
  • 1970-01-01
  • 2020-09-27
  • 1970-01-01
  • 1970-01-01
  • 2021-05-31
相关资源
最近更新 更多