如何将画布另存为png图像?


80

我有一个带有绘图的画布元素,我想创建一个按钮,当单击该按钮时,它将图像保存为png文件。所以它应该打开保存,打开,关闭对话框...

我用这段代码

var canvas = document.getElementById("myCanvas");
window.open(canvas.toDataURL("image/png"));

但是,当我在IE9中对其进行测试时,会打开一个新窗口,显示“无法显示该网页”,其网址为:

data:image / png; base64,iVBORw0KGgoAAAANSUhEUgAAAmAAAABpCAYAAACd + 58xAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAADRwSURBVHhe7V0HgBVF0q7ZJSlJwRxAPUFRD39RFLN34qGnnomoqIjhzBlFPROIgsoZzogR5AQEzJ4BPFAUEUwgJjgQkCQKooggaf / 6el6 / 6ZnpSW / zUn237u5MdXX1172 + z6rqaqeEG6VsJet + PDW / vkdrfx3H3yfT2tVzaP26X6hkw1q / BoeI / 280 / 29JwznZxJPUyXtBQBAQBAQBQaBcECjefmi56BWlZYtAeqajx / WokfrJYEqOIikOFRfXoVq161PtOk2odu0t + ectqKiojnrntWhC46QhYOtXfUarl79Ivy9 / ldau + H + TX / 8b2SbjJ07pWFQy2Uqnp2yXSrQJAoKAICAICALJCAgBS8ao8iTi / UvpSZlBxiwqwWOKimsxCWtEdettR3XqbEfFtRonkrBYArZh3fe0 + senadWyEbRm1UzasP53K45ZiFc84RKyVXkbVUYWBAQBQUAQyIqAELCsiFW2fDQpSyZk8UQMMysqKmaPWCOqt8mOVK / eTuQU1YuccCQBW7dyIq38 / J5A / fN的/ ad3a5QGXmqsvLfGKJl0ZCFdONEOPyl5lGV8QEAQEAUGghiMgBKzqLHCeHqVOrILtduF4MpZExEqoVq167A3bmjap34J / bmoFqcj2dM3Pr9GK + b1p5bJXmXz9nEC + 3FiorYF4hcmXlo + gUrk + um / + e + QoVWfxxRJBQBAQBAQBQUAQqBwE8uzCwiMiaEqOWYR5jJ2 / 6Hl58nYHk0Pr1v1Ov62cTytXfE5r1yyyc6RgDhjI16 + L + tLqFZ9xnteGUKc0Xi876YpYkFD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AeSMgHrDyRrj0 + rOEGvVoYY9Y0inIeE + YQQ + cqGGj3dgDtvJjC / mKm7BHmG68lGjO + 0T

有人知道怎么修这个东西吗?


Answers:


65

试试这个:

var c=document.getElementById("alpha");
var d=c.toDataURL("image/png");
var w=window.open('about:blank','image from canvas');
w.document.write("<img src='"+d+"' alt='from canvas'/>");

这会在新页面上显示画布上的图像,但是如果您进行了open popup in new tab设置,它将显示about:blank在地址栏中。

编辑:-尽管window.open("<img src='"+ c.toDataURL('image/png') +"'/>")在FF或Chrome中不起作用,但是尽管渲染与画布上显示的有所不同,但以下工作可行,但我认为透明度是问题所在:

window.open(c.toDataURL('image/png'));

它在此命令上崩溃:var w = window.open('about:blank','canvas from canvas');
偷偷摸摸的

4
我将其更改为:var w = window.open('about:blank');,现在图像在新窗口中打开,但是如何获取它以便保存关闭框,我不这样做想要右键单击图像并单击另存为...
偷偷摸摸的

31

FileSaver.js应该可以在这里为您提供帮助。

var canvas = document.getElementById("my-canvas");
// draw to canvas...
canvas.toBlob(function(blob) {
    saveAs(blob, "pretty image.png");
});

13
有很多并不在IE9工作:-(相当多的可以固定polyfills但恐怕这是超出如果我可以建议使用谷歌Chrome Frame的使用IE的用户。
莫里斯

Safari不支持@VagueExplanation toBlob()。但是可以在此处找到一个简单的polyfill:developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/…–
Maurice

18

我使用此解决方案来设置文件名

HTML:

<a href="#" id="downloader" onclick="download()" download="image.png">Download!</a>
<canvas id="canvas"></canvas>

JavaScript:

function download(){
    document.getElementById("downloader").download = "image.png";
    document.getElementById("downloader").href = document.getElementById("canvas").toDataURL("image/png").replace(/^data:image\/[^;]/, 'data:application/octet-stream');
}

11

我遇到了这个问题,这是没有任何外部或其他脚本库的最佳解决方案:在Javascript标记或文件中创建此函数:我们在这里假设canvas是您的canvas:

function download(){
        var download = document.getElementById("download");
        var image = document.getElementById("canvas").toDataURL("image/png")
                    .replace("image/png", "image/octet-stream");
        download.setAttribute("href", image);

    }

在HTML的主体部分中,指定按钮:

<a id="download" download="image.png"><button type="button" onClick="download()">Download</button></a>

这正在工作,下载链接看起来像一个按钮。在Firefox和Chrome中进行了测试。


1
不幸的是,在IE 11中,它清除了屏幕并将URL更改为:data:image / octet-stream; base64,iVBORw
Mike

9

为了适应所有三点:

  • 纽扣
  • 将图像另存为png文件
  • 打开保存,打开,关闭对话框

文件对话框是浏览器中的设置。

对于按钮/保存部分,将以下功能(从其他答案中总结出来)分配给按钮onclick:

function DownloadCanvasAsImage(){
    let downloadLink = document.createElement('a');
    downloadLink.setAttribute('download', 'CanvasAsImage.png');
    let canvas = document.getElementById('myCanvas');
    let dataURL = canvas.toDataURL('image/png');
    let url = dataURL.replace(/^data:image\/png/,'data:application/octet-stream');
    downloadLink.setAttribute('href', url);
    downloadLink.click();
}

Codepen示例

另一种更干净的方法是使用Canvas.toBlob()

function DownloadCanvasAsImage(){
    let downloadLink = document.createElement('a');
    downloadLink.setAttribute('download', 'CanvasAsImage.png');
    let canvas = document.getElementById('myCanvas');
    canvas.toBlob(function(blob) {
      let url = URL.createObjectURL(blob);
      downloadLink.setAttribute('href', url);
      downloadLink.click();
    });
}

Codepen示例

两种解决方案都不与100%跨浏览器兼容,因此请检查客户端


在花了很多时间寻找解决方案之后,THIS才是对我有用的解决方案。在我使用的Firefox 76.0.1(64位)上。我应该检查其他浏览器,但我希望所有最新的浏览器仍然可以使用。
艾伦·斯图尔特

4

我也许发现了一种更好的方法,可以不强制用户右键单击并将图像另存为。实时将canvas base64代码绘制到href链接的中,然后对其进行修改,以便下载将自动开始。我不知道它是否与浏览器普遍兼容,但是它应该与主要/新浏览器兼容。

var canvas = document.getElementById('your-canvas');
    if (canvas.getContext) {
        var C = canvas.getContext('2d');
    }

$('#your-canvas').mousedown(function(event) {
    // feel free to choose your event ;) 

    // just for example
    // var OFFSET = $(this).offset();
    // var x = event.pageX - OFFSET.left;
    // var y = event.pageY - OFFSET.top;

    // standard data to url
    var imgdata = canvas.toDataURL('image/png');
    // modify the dataUrl so the browser starts downloading it instead of just showing it
    var newdata = imgdata.replace(/^data:image\/png/,'data:application/octet-stream');
    // give the link the values it needs
    $('a.linkwithnewattr').attr('download','your_pic_name.png').attr('href',newdata);

});

您可以随意包装<a>任何东西。


0

试试这个:

jQuery('body').after('<a id="Download" target="_blank">Click Here</a>');

var canvas = document.getElementById('canvasID');
var ctx = canvas.getContext('2d');

document.getElementById('Download').addEventListener('click', function() {
    downloadCanvas(this, 'canvas', 'test.png');
}, false);

function downloadCanvas(link, canvasId, filename) {
    link.href = document.getElementById(canvasId).toDataURL();
    link.Download = filename;
}

您只需将此代码放入firefox或chrom中的控制台中,并在上述脚本中更改了画布标签ID之后,即可在控制台中运行此脚本。

执行完此代码后,您将在html页面底部看到链接为文本“ click here”。单击此链接,然后在新窗口中将画布图形作为PNG图像打开,然后保存图像。


0

提交一个包含带有canvas值的输入的表单toDataURL('image / png')例如

// JAVASCRIPT

    var canvas = document.getElementById("canvas");
    var url = canvas.toDataUrl('image/png');

将url的值插入到form元素上的隐藏输入中。

// PHP

    $data = $_POST['photo'];
    $data = str_replace('data:image/png;base64,', '', $data);
    $data = base64_decode($data);
    file_put_contents("i".  rand(0, 50).".png", $data);

效果很好,除了JavaScript函数canvas.toDataUrl(...)应该为canvas.toDataURL(...)
布兰农

0

完整的HTML代码。剪切并粘贴到新的.HTML文件中:

包含两个示例:

  1. HTML文件中的画布。
  2. 用Javascript动态创建的画布。

测试于:

  1. IE浏览器
  2. *边缘(标题名称不显示)
  3. 火狐浏览器
  4. 歌剧

<!DOCTYPE HTML >
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title> #SAVE_CANVAS_TEST# </title>
    <meta 
        name   ="author" 
        content="John Mark Isaac Madison"
    >
    <!-- EMAIL: J4M4I5M7 -[AT]- Hotmail.com -->
</head>
<body>

<div id="about_the_code">
    Illustrates:
    <ol>
    <li>How to save a canvas from HTML page.     </li>
    <li>How to save a dynamically created canvas.</li>
    </ol>
</div>

<canvas id="DOM_CANVAS" 
        width ="300" 
        height="300"
></canvas>

<div id="controls">
    <button type="button" style="width:300px;"
            onclick="obj.SAVE_CANVAS()">
        SAVE_CANVAS ( Dynamically Made Canvas )
    </button>

    <button type="button" style="width:300px;"
            onclick="obj.SAVE_CANVAS('DOM_CANVAS')">
        SAVE_CANVAS ( Canvas In HTML Code )
    </button>
</div>

<script>
var obj = new MyTestCodeClass();
function MyTestCodeClass(){

    //Publically exposed functions:
    this.SAVE_CANVAS = SAVE_CANVAS;

    //:Private:
    var _canvas;
    var _canvas_id = "ID_OF_DYNAMIC_CANVAS";
    var _name_hash_counter = 0;

    //:Create Canvas:
    (function _constructor(){
        var D   = document;
        var CE  = D.createElement.bind(D);
        _canvas = CE("canvas");
        _canvas.width = 300;
        _canvas.height= 300;
        _canvas.id    = _canvas_id;
    })();

    //:Before saving the canvas, fill it so
    //:we can see it. For demonstration of code.
    function _fillCanvas(input_canvas, r,g,b){
        var ctx = input_canvas.getContext("2d");
        var c   = input_canvas;

        ctx.fillStyle = "rgb("+r+","+g+","+b+")";
        ctx.fillRect(0, 0, c.width, c.height);
    }

    //:Saves canvas. If optional_id supplied,
    //:will save canvas off the DOM. If not,
    //:will save the dynamically created canvas.
    function SAVE_CANVAS(optional_id){

        var c = _getCanvas( optional_id );

        //:Debug Code: Color canvas from DOM
        //:green, internal canvas red.
        if( optional_id ){
            _fillCanvas(c,0,255,0);
        }else{
            _fillCanvas(c,255,0,0);
        }

        _saveCanvas( c );
    }

    //:If optional_id supplied, get canvas
    //:from DOM. Else, get internal dynamically
    //:created canvas.
    function _getCanvas( optional_id ){
        var c = null; //:canvas.
        if( typeof optional_id == "string"){
            var id = optional_id;
            var  d = document;
            var c  = d.getElementById( id );
        }else{
            c = _canvas; 
        }
        return c;
    }

    function _saveCanvas( canvas ){
        if(!window){ alert("[WINDOW_IS_NULL]"); }

        //:We want to give the window a unique
        //:name so that we can save multiple times
        //:without having to close previous
        //:windows.
        _name_hash_counter++              ; 
        var NHC = _name_hash_counter      ;
        var URL = 'about:blank'           ;
        var name= 'UNIQUE_WINDOW_ID' + NHC;
        var w=window.open( URL, name )    ;

        if(!w){ alert("[W_IS_NULL]");}

        //:Create the page contents,
        //:THEN set the tile. Order Matters.
        var DW = ""                        ;
        DW += "<img src='"                 ;
        DW += canvas.toDataURL("image/png");
        DW += "' alt='from canvas'/>"      ;
        w.document.write(DW)               ;
        w.document.title = "NHC"+NHC       ;

    }

}//:end class

</script>

</body>
<!-- In IE: Script cannot be outside of body.  -->
</html>

0

我真的很喜欢Tovask的答案,但是由于该函数具有名称download此答案,说明了原因)。我也看不到将“ data:image / ...”替换为“ data:application / ...”的意义。

以下代码已经在Chrome和Firefox中进行了测试,似乎在这两种代码中均能正常工作。

JavaScript:

function prepDownload(a, canvas, name) {
    a.download = name
    a.href = canvas.toDataURL()
}

HTML:

<a href="#" onclick="prepDownload(this, document.getElementById('canvasId'), 'imgName.png')">Download</a>
<canvas id="canvasId"></canvas>

-1
var canvasId = chart.id + '-canvas';
var canvasDownloadId = chart.id + '-download-canvas';
var canvasHtml = Ext.String.format('<canvas id="{0}" width="{1}" height="{2}"></canvas><a id="{3}"/>',
canvasId,
chart.getWidth(),
chart.getHeight(),
canvasDownloadId);
var canvasElement = reportBuilder.add({ html: canvasHtml });

var canvas = document.getElementById(canvasId);

var canvasDownload = document.getElementById(canvasDownloadId);
canvasDownload.href = chart.getImage().data;
canvasDownload.download = 'chart';

canvasDownload.click();
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.