Fabricjs - 在事件中创建"added"的对象未被 loadFromJSON 完全恢复



当我尝试将画布序列化为JSON时,我遇到了一个问题,然后用LoadFromjson还原。

以下JSFIDDLE只是一个较大项目的摘录,但显示了问题:

https://jsfiddle.net/3y97d7nj/1/

fabric.MyRect = fabric.util.createClass(fabric.Rect, {
    type: "myRect",
    initialize(options={}){
    this.callSuper("initialize", options)
    this.on("moving", function(){
        if(this.tri){
        this.tri.top = this.getTop()
        this.tri.left = this.getLeft()
        this.tri.setCoords()
      }
    })
    this.on("added", function(){        
        this.tri = new fabric.Triangle({
        left: this.getLeft(),
        top: this.getTop(),
        width: 20,
        height: 20,
        fill: "red"
      })
        this.canvas.add(this.tri)
    })
  }
})
fabric.MyRect.fromObject = function(obj){
    return new fabric.MyRect(obj)
}
let c = new fabric.Canvas("mycanvas")
c.add(new fabric.MyRect({
    top:0,
  left:0,
  width:100,
  height:100,
  fill:"green"
 }))
c.add(new fabric.MyRect({
    top:100,
  left:100,
  width:100,
  height:100,
  fill:"blue"
 }))
c.renderAll()
let canvasModel = c.toObject()
canvasModel.objects = canvasModel.objects.filter(e => e.type !== "triangle")
c.clear()
c.loadFromJSON(JSON.stringify(canvasModel), c.renderAll.bind(c))

MyRect子类从"对象:添加"回调中"添加"到画布中时添加了一个新的三角形。如果我不在画布上添加myrect的第二个实例(行:39),一切正常,但是我会像以下情况下遇到问题,两个myrect实例。

如果您运行小提琴,则两个myrect实例都在画布上呈现,但是只有一个是从"对象:添加"回调的三角形附加的三角形。

我不确定是否打算"对象:添加"回调是为了在画布中添加更多对象。但是如上文字,这只是一个更大的应用程序的提取

我正在使用版本:1.6.2

问题发生在最近的铬和firefox中。

任何帮助都非常感谢。

最好的问候,Jan

问题是,三角形没有在帆布中再次添加,我不知道为什么,看一下小提琴,我手动添加了第一个三角形,因为没有添加到画布中:

      fabric.MyRect = fabric.util.createClass(fabric.Rect, {
    type: "myRect",
    initialize(options={}){
      this.callSuper("initialize", options)
      this.on("moving", function(){
      console.log('tri', this.tri)
        if(this.tri){
          this.tri.top = this.getTop()
          this.tri.left = this.getLeft()
          this.tri.setCoords()
        }
      })
      this.on("added", function(){              
        this.tri = new fabric.Triangle({
          left: 0,
          top: 0,
          width: 20,
          height: 20,
          fill: "red"
        })
        this.tri.id = parseInt(Math.random() * 100000)
        console.log('add', this.tri, this.tri.id)
        this.canvas.add(this.tri)
      })
    }
  })
  fabric.MyRect.fromObject = function(obj){
    return new fabric.MyRect(obj)
  }
  window.c = new fabric.Canvas("mycanvas")
  c.add(new fabric.MyRect({
    top:0,
    left:0,
    width:100,
    height:100,
    fill:"green"
   }))
  c.add(new fabric.MyRect({
    top:100,
    left:100,
    width:100,
    height:100,
    fill:"blue"
   }))
  c.renderAll()
  let canvasModel = c.toObject()
  canvasModel.objects = canvasModel.objects.filter(e => e.type !== "triangle")
  c.clear()
  console.log('canvasmodel', canvasModel)
  c.loadFromJSON(JSON.stringify(canvasModel), c.renderAll.bind(c))
  c.add(c._objects[0].tri)
  c.renderAll()

https://jsfiddle.net/davidtorroija/3y97d7nj/2/

最新更新