Recreate Fabric.js canvas and export as an image?

11,796

Fabric has a built in function to convert to data urls. You can use the download property of a link to make the link a download link. Finally you can use the DOM click() function to emulate clicking the download link. The end result is:

function download(url,name){
// make the link. set the href and download. emulate dom click
  $('<a>').attr({href:url,download:name})[0].click();
}
function downloadFabric(canvas,name){
//  convert the canvas to a data url and download it.
  download(canvas.toDataURL(),name+'.png');
}

now when you want to download the canvas call

downloadFabric(canvas,'<file name>');
Share:
11,796
Arco_Pelago
Author by

Arco_Pelago

Updated on June 23, 2022

Comments

  • Arco_Pelago
    Arco_Pelago almost 2 years

    I have a canvas where the user can create a design using images in another div that they click, sending it to the Fabric.js canvas where it gets moved around and so on. Since the canvas's size is width="270"and height="519", smaller than what the finished product is, I need to recreate it with a canvas that has the size width="1001"and height="1920" and then screenshot it so that I get it all in 1 single image. How do I do this?

    This is what my code looks like so far:

    HTML

    <div id="CanvasContainer">
        <canvas id="Canvas" width="270" height="519"></canvas>
    </div>
    

    CSS

    #CanvasContainer {
        width: 270px;
        height: 519px;
        margin-left: 15px;
    }
    #Canvas {
        overflow: hidden;
    }
    

    JAVASCRIPT

    //Defining Canvas and object array
    var canvas = new fabric.Canvas('Canvas');
    
    //When clicked
    $(document).ready(function () {
        $("#Backgrounds img").click(function () {
            var getId = $(this).attr("id");
    
            //adding all clicked images
            var imgElement = document.getElementById(getId);
            var imgInstance = new fabric.Image(imgElement, {
                left: 135,
                top: 259,
                width: 270,
                height: 519
            });
            //Corner color for clicked images
            imgInstance.set({
                borderColor: 'white',
                cornerColor: 'black',
                transparentCorners: false,
                cornerSize: 12
            });
            canvas.add(imgInstance);
        });
    });