javascript - 将 Canvas 下载为 PNG 图像

标签 javascript html canvas download png

<分区>

当我尝试将我的 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>

关于javascript - 将 Canvas 下载为 PNG 图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36986476/

相关文章:

javascript - C# .NET OnClientClick 返回 true 但 OnClick 未触发

javascript - AngularJS:使用基于选择的过滤器后,如果仅限于单个属性,则不会清除

php - 如果 url 包含正确的字符串,则更改导航栏中的背景颜色

javascript - 比较 HTML5 Canvas 中的两种字体

javascript - 给从 Flash/ActionScript 3 迁移过来的新 JavaScript 开发人员的建议?

javascript - jQuery 动画不适用于 iframe 内容

javascript - 切换标签后如何保持滚动位置?

javascript - 重置/取消选中/选择问卷/调查中的用户选择

javascript - 一键切换div内容

javascript - 无法发布消息(CanvasRenderingContext2D)