element11
element11

Reputation: 4485

Loading and storing svg files in fabricjs

I have been able to put together a small test example for loading and displaying SVG files on a canvas with fabricjs.

What I would like to do is store the loaded SVG in a variable so it can be added to canvas outside the scope of the loadSVGFromURL callback method. I would like to be able to add the same SVG to the canvas many times throughout the lifecycle of the program without having to load the file again and again.

When I try this svg is undefined. Can anyone tell me how I can do this?

function start(){
    var canvas = new fabric.Canvas('canv');
    canvas.setWidth(800);
    canvas.setHeight(600);
    canvas.hoverCursor = 'normal';

    var svg;

    fabric.loadSVGFromURL('svg/test.svg', function(objects, options) {
        var obj = fabric.util.groupSVGElements(objects, options);
        obj.set({
            left: 50,
            top: 50
        });

        obj.hasControls = false;
        obj.padding = 10;

        canvas.add(obj);      
        svg = obj;
    });

    render();
    canvas.add(svg);

}

function render(){ 
    canvas.renderAll();
    fabric.util.requestAnimFrame(render);
}

Upvotes: 1

Views: 1456

Answers (1)

element11
element11

Reputation: 4485

I have discovered that loadSVGFromURL is asynchronous, so we need to make sure it has loaded first. We can call a function to load the object and store it in some global namespace like SVG.

When we know it has been loaded, we can use fabric.util.object.clone() to clone the object and add to canvas.

var SVG = SVG || {};

function addTestObj() {
    if(SVG.testObject) {
        var clone = fabric.util.object.clone(SVG.testObject);
         clone.set({
             left: x,
             top: y
         });

         canvas.add(clone);
    }
}

function start() {
    var canvas = new fabric.Canvas('canv');
    canvas.setWidth(800);
    canvas.setHeight(600);
    canvas.hoverCursor = 'normal';

    fabric.loadSVGFromURL('svg/test.svg', function(objects, options) {
        var obj = fabric.util.groupSVGElements(objects, options);

        obj.hasControls = false;
        obj.padding = 10;

        SVG.testObject = obj;

    });

    render();

}

function render() { 
    canvas.renderAll();
    fabric.util.requestAnimFrame(render);
}

Upvotes: 1

Related Questions