简体   繁体   中英

Can't save canvas as image on Edge browser

I am using fabric js for my web application. For saving HTML5 canvas as image using fabric js, I found the following code which works in chrome and firefox browser. But when i run th same code in microsoft edge, the browser just opens a blank new window without any image on it.

 $(".save").click(function () {
    canvas.deactivateAll().renderAll();
    window.open(canvas.toDataURL('png'));
});

However I also tested many fiddle projects which shows how to convert canvas to an image. Those fiddles works on chrome but not in edge. An example fiddle is here

If you will use FileSaver.js it will download on Edge. For using FileSaver.js you need to convert base64 data into the blob data. To do that, please check this post on StackOverflow

Here is an updated fiddle

You need to include FileSaver.js into your project, and your save button will have the following code:

$("#canvas2png").click(function(){
    canvas.isDrawingMode = false;

    if(!window.localStorage){alert("This function is not supported by your browser."); return;}

    var blob = new Blob([b64toBlob(canvas.toDataURL('png').replace(/^data:image\/(png|jpg);base64,/, ""),"image/png")], {type: "image/png"});
      saveAs(blob, "testfile1.png");
});

Alternative, quick and dirt solution is to write html data into new tab, and right click on the image and save it. This solution is not required any plugins or libraries.

Your save will simply change to:

  $("#canvas2png").click(function(){
    canvas.isDrawingMode = false;

    if(!window.localStorage){alert("This function is not supported by your browser."); return;}

       var html="<img src='"+canvas.toDataURL()+"' alt='canvas image'/>";
        var newTab=window.open();
        newTab.document.write(html);
});

Check the modified fiddle:

http://jsfiddle.net/9hrcp/164/

document.getElementById('test').src = canvas.toDataURL('image/png');

i added an image tag and and set the src attribute to the dataUrl to the image and it loads fine.

So edge is generating a correct png, is refusing to load it as a dataUrl redirect. May be a feature and not a bug.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM