简体   繁体   中英

Saving canvas as a PNG or JPG

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.

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
});

canvas.toDataURL('png') provides a string a la data:image/png;base64,XYZ . You could stuff that into an <a href="%dataURI%" download>download</a> (possibly trigger a click event on the element). See Downloading resources in HTML5: a[download]

Currently supported only by Google Chrome, though.

In script.js file

  $(document).on('click','#btnPreview',function(){
     var img =$scope.canvas.toDataURL('image/png');
     $.ajax({
                type: "POST",   
                url: 'ajax.php', 
                data: {'img':img},
                success: function(data) { 
                    $("#loader_message").html("Image saved successfully"); 
                }
            });
  });

In ajax.php

    $encodedData=explode(',', $_POST["img"]);
    $data = base64_decode($encodedData[1]);
    $urlUploadImages = $_SERVER['DOCUMENT_ROOT'].$projName.'/images/canvas/';
    $nameImage = "test.png";
    $img = imagecreatefromstring($data);
     if($img) {
        imagepng($img, $urlUploadImages.$nameImage, 0);
        imagedestroy($img); 
        echo "OK";
    }
    else {
        echo 'ERROR';
    }

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