Saving canvas as a PNG or JPG

UXX1 picture UXX1 · Jun 26, 2012 · Viewed 16.4k times · Source

I want to save canvas as PNG, without opening it in a new window as base64-encoded image.

I used this code:

jQuery("#btnPreview").click(function(){
        if (!fabric.Canvas.supports('toDataURL')) {
            alert('Sorry, your browser is not supported.');
        }
        else {
            canvas.deactivateAll();
            canvas.forEachObject(function(o){
                if(o.get("title") == "||Watermark||"){
                    canvas.bringToFront(o);
                }
            });
            window.open(canvas.toDataURL('png'), "");
            canvas.forEachObject(function(o){
                if(o.get("title") == "||Watermark||"){
                    canvas.sendToBack(o);
                }
            });
            canvas.renderAll();
        }

    });

I want to make the button save the image as a PNG or JPG.

Answer

Dakshika picture Dakshika · Feb 14, 2014

I use this on my jquery:

var image = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream"); 

$('.save').attr({
    'download': 'YourProduct.png',  /// set filename
    'href'    : image              /// set data-uri
});