Search code examples
fabricjs

Fabric.js : not load groups that contain SVG from JSON


I want to group a text with an SVG but groups that contained SVG don't restore from json, my code is :

let canvas = new fabric.Canvas(this.$refs.canvas);
      let waitSvgLoad = new Promise((resolve)=>{
      fabric.loadSVGFromURL(require('@/assets/img/desk.svg'), objects => {
         let obj = fabric.util.groupSVGElements(objects, {
         top: 30,
         left: 30,
       })
      resolve(obj)
      })
})
waitSvgLoad.then((svg)=>{
   let text = new fabric.Text('test', {
   left: 20,
   top: 20
    })
  let group = new fabric.Group([ text ,svg], {
  left: 150,
  top: 100,
});
canvas.add(group)
canvas.clear()
let jsontest = JSON.stringify(canvas)
canvas.loadFromJSON(jsontest)
canvas.renderAll.bind(canvas)
})

Solution

  • thanks to krillea...@gmail.com that help me in google group https://groups.google.com/g/fabricjs/c/n5ngMPSiYNs i debug project and determin below code is the problem :

    fabric.Object.prototype.toObject = (function(toObject) {
        return function() {
           return fabric.util.object.extend(toObject.call(this), {
              selectable: this.selectable,
              hasControls: this.hasControls,
              deskId: this.deskId,
              typeShape: this.typeShape
    })
    }
    })(fabric.Object.prototype.toObject)
    

    in fact, custom attributes were the problem so I replace the top code with this:

    JSON.stringify(this.canvas.toJSON(['_controlsVisibility','deskId','typeShape']))
    

    and solved my problem