Marak Daga
Marak Daga

Reputation: 51

fabric.js loading a SVG as an object

Im currently working with fabric.js and am attempting to load a SVG and have similar functionality as i do currently with rectangles (which i used to test)

What i can currently do is create a box1.on('moving', function() { movetobox(box1a, box1) });

to move a second rect(im refering to their objects as box1a and box1) to always be ontop of another.

But if i load a SVG, i am getting an undefined error when trying to refer to it using a on('moving').

i have created a JSfiddle to show my code easier

https://jsfiddle.net/marak/5tvdu532/?utm_source=website&utm_medium=embed&utm_campaign=5tvdu532

now this works for rects:

box1.on('moving', function() {
  movetobox(box1a, box1)
});

but this doesnt work for SVG's

box1SVG.on('moving', function() {
  moveSVGtobox();
});

(note both functions do the same thing, their on the JSFiddle).

Is there another way to load in a SVG that allows me to reference it the same as a rect? Im going to have quite a few of them, and each has to be able to align with different objects and be accessable through code.

Upvotes: 0

Views: 2665

Answers (1)

Marak Daga
Marak Daga

Reputation: 51

Found a solution.

Inside of the creation script for the SVG i added this: name="test"

fabric.loadSVGFromURL('http://localhost/pgl/images/marakrough.svg', function(objects, options) { 
    var shape = new fabric.util.groupSVGElements(objects, options);
    canvas.add(shape.scale(1));
    shape.set({ left: 200, top: 100, name: "test" }).setCoords();
    canvas.add(shape);

this allowed me to build an array later of all objects on the canvas after i have added them using this:

var objs = canvas.getObjects();

and search through that for any with a name of test which i then assigned to another variable.

var testOb = objs[1];

this i was able to make direct modifications on with no issues (so far)

testOb.left += 1;

Im not sure if this is HOW its supposeto be used, but by 5am, im just happy its working.

Cheers, Marak

Upvotes: 1

Related Questions