javascriptsvgcanvasfabricjs

TypeError (is not iterable) when adding SVG to FabricJS canvas


I have a fabricjs canvas, and I'm trying to add an SVG to it. But whatever I do, I get problems. It keeps saying: "Uncaught (in promise) TypeError: t is not iterable".

let svg = `<svg viewBox="-8 -8 136 136">
<path stroke="#000000" stroke-width="8" d="m0 51.82677l0 0c0 -28.623135 23.203636 -51.82677 51.82677 -51.82677l0 0c13.745312 0 26.927654 5.4603047 36.64706 15.17971c9.719406 9.719404 15.17971 22.901749 15.17971 36.64706l0 0c0 28.623135 -23.203636 51.82677 -51.82677 51.82677l0 0c-28.623135 0 -51.82677 -23.203636 -51.82677 -51.82677zm25.913385 0l0 0c0 14.311565 11.60182 25.913387 25.913385 25.913387c14.311565 0 25.913387 -11.601822 25.913387 -25.913387c0 -14.311565 -11.601822 -25.913385 -25.913387 -25.913385l0 0c-14.311565 0 -25.913385 11.60182 -25.913385 25.913385z" fill="none"></path>
</svg>`;

let canvas = new fabric.Canvas("canvas");
let path = fabric.loadSVGFromString(svg, function(objects, options) {
    let obj = fabric.util.groupSVGElements(objects, options);
    
    obj.set({
        left: canvas.width / 2 - obj.width / 2,
        top: canvas.height / 2 - obj.height / 2
    });
    canvas.add(obj).renderAll();
});

Hopefully someone can help me out


Solution

  • For Fabric > 6.0.0 use this:

      fabric.loadSVGFromString(svg).then((result) => {
        canvas.add(...(result.objects.filter((obj) => !!obj)))renderAll();
      });