Platon
Platon

Reputation: 84

Fabric js load svg from url missing properties

I'm trying to use loadSVGfromURL and everything fine, but I have some problems with text.

If i'm trying to load text some properties like font-family, fill, etc... are not loaded. The text is loaded, but with default properties: black color, and Times new roman font.

Here is my code:

fabric.loadSVGFromURL(img.src, function(objects, options) {
    var tmpobj = fabric.util.groupSVGElements(objects, options);
    canvas.setDimensions({
        width : tmpobj.width,
        height : tmpobj.height
    });
    //canvas.clear();
    canvas.forEachObject(function(obj) {
        //var obj = new fabric.Object({ padding: 0 });
        var obj = objects[i];
        if (obj.get('type') == 'text') {
            var text = new fabric.IText('Tap and Type', {
                fontFamily : obj.get('fontFamily'),
                left : obj.get('left'),
                top : obj.get('top'),
                text : obj.get('text'),
                oCoords : obj.get('oCoords'),
                fontSize : obj.get('fontSize'),
                height : obj.get('height'),
                width : obj.get('width'),
                fill : obj.get('fill')
            });
            obj = text;
        }
        obj.padding = 0;
        obj.setCoords();
        canvas.add(obj);
        canvas.renderAll();
    });
})

Upvotes: 2

Views: 1177

Answers (2)

Platon
Platon

Reputation: 84

I have added this var svg = doc;
for (var i = 0; i < svg.childNodes.length; i++) {

      if (svg.childNodes[i].tagName == "text") {
          for (var j = 0; j < svg.childNodes[i].childNodes.length; j++) {
              if (svg.childNodes[i].childNodes[j].tagName == "tspan") {
                  for (var k = 0; k < svg.childNodes[i].childNodes[j].classList.length; k++)
                  {
                      var tmpClassName = svg.childNodes[i].childNodes[j].classList[k];
                      svg.childNodes[i].classList.add(tmpClassName);
                  }



              }
          }
      }
  }

in the

fabric.parseSVGDocument

function to add my tspan styles to text styles

Upvotes: 0

AndreaBogazzi
AndreaBogazzi

Reputation: 14741

The problem is missing TSPAN support in fabricjs.

The svg looks like this:

<text x="32" y="40" class="cls-1"><tspan class="cls-2">riev</tspan></text>
  <text x="158" y="211" class="cls-1"><tspan class="cls-3">0999989878</tspan></text>
  <text x="96" y="120" class="cls-1"><tspan class="cls-2">Platon</tspan></text>

The information class="cls-2" and class="cls-3" does not get parsed because the tspan are discarded.

You can modify the svg like this:

<text x="32" y="40" class="cls-1 cls-2"><tspan >riev</tspan></text>
  <text x="158" y="211" class="cls-1 cls-3"><tspan >0999989878</tspan></text>
  <text x="96" y="120" class="cls-1 cls-2"><tspan >Platon</tspan></text>

to get it parsed.

Upvotes: 1

Related Questions