How to save canvas as an image(Chrome, Firefox, IE)

 

Save canvas as an image in chome and firefox is easy, the code below will work.

....
function saveAsImage(ele){
    var c=document.getElementById("myCanvas");
    var image = c.toDataURL().replace("image/png", "image/octet-stream");
    ele.download = 'image.png';
    ele.href = image;
}
....
<body>
    ...
    <a href="javascript:void(0)" onclick="saveAsImage(ele)">downloadCanvas</a>
    ...
<body>

But, in IE(obsolutely in IE>=9), the code does not work, after some investigation in MSDN, I found a work around:

function saveAsPng(ele){
    window.BlobBuilder = window.BlobBuilder || window.MSBlobBuilder || 
           window.WebKitBlobBuilder || window.MozBlobBuilder;
    var toBlob = c.toBlob || c.msToBlob;
    var saveBlob = window.navigator.saveBlob || window.navigator.msSaveBlob;
    if(window.BlobBuilder && toBlob && saveBlob){
        var blobBuilder = new window.BlobBuilder();
        blobBuilder.append(toBlob.bind(c)());
        saveBlob.bind(window.navigator)(blobBuilder.getBlob(), "image.png");
    }else{
        var image = c.toDataURL().replace("image/png", "image/octet-stream");
        ele.download = 'image.png';
        ele.href = image;
    }
}

The “BlobBuilder”, “toBlob” and “saveBlob” methods can use in MS browser, so we use these methods to recognize MS browser.

Leave a Reply

Your email address will not be published. Required fields are marked *

You must enable javascript to see captcha here!