使用Fabric.JS覆盖自定义类的getter和setter

时间:2020-09-04 16:06:51

标签: javascript html5-canvas fabricjs

我目前正在使用Fabric.JS来创建一个工具来轻松地图解社交情况。为此,我创建了一个由图像和文本组成的自定义图形对象(更确切地说是一个自定义组)。

我正在使用一个名为label的自定义属性,其中包含在text元素中显示的文本值。这些技巧在对象初始化(将标签值放入文本元素)中效果很好,但之后不再起作用。我必须使用forceSync()函数手动更新文本值(似乎永远不会调用_render方法,并且标签设置程序都不会覆盖这两个值)

有正确的方法吗?另一种替代setter或观看自定义类属性的技巧的方法是什么?

类代码

this.GraphicRessource = fabric.util.createClass(fabric.Group, {

    type: 'GraphicRessource',
  // initialize can be of type function(options) or function(property, options), like for text.
  // no other signatures allowed.
  initialize: function(property,options) {
    options || (options = { });
    this.callSuper('initialize', property, options);
    this.set('id', options.id || '');
    this.set('label', options.label || '');
    this.height += 20;
    this.item(1).set({text:this.label,top: this.item(1).get("top") + 10});
  },
  set label(value){
    console.log("new label set");
    this.item(1).set('text',value);
  },
  toObject: function() {
    return fabric.util.object.extend(this.callSuper('toObject'), {
      label: this.get('label')
    });
  },
  forceSync:function(){
    this.item(1).set('text',this.label);
  },
  _render: async function(ctx) {
    this.item(1).set({text:this.label,top: this.item(1).get("top") + 10});
    await this.callSuper('_render', ctx);
    this.item(1).bringToFront();
  }
});

对象初始化

fabric.Image.fromURL('url', function(image) {
        image.originX = 'center';
        image.originY = 'bottom';
        let text = new fabric.Text("sample", {
          fontFamily: 'Font',
          originX: 'center',
          originY: 'bottom',
          stroke: '#33aa33',
          fontSize: 10
        });
        image.scaleToWidth(100);
        let ressource = new vm.GraphicRessource([image,text],{label:"Some Text Here",id:vm.idCounter});
        vm.canvas.add(ressource);
        vm.idCounter+=1;
      });

0 个答案:

没有答案