【问题标题】:FabricJs - How do I Add properties to each objectFabricJs - 如何向每个对象添加属性
【发布时间】:2016-12-03 04:36:22
【问题描述】:

我需要为现有的对象属性集引入一些额外的属性。

喜欢:

  1. 身份证
  2. 地理位置

每当我绘制一个形状时,我都需要给形状添加额外的属性并且需要从toDataLessJSON()获取

【问题讨论】:

    标签: fabricjs


    【解决方案1】:

    从 1.7.0 版开始,levon 的代码停止工作。您需要做的就是修复如下:

    // Save additional attributes in Serialization
    fabric.Object.prototype.toObject = (function (toObject) {
        return function (properties) {
            return fabric.util.object.extend(toObject.call(this, properties), {
                textID: this.textID
            });
        };
    })(fabric.Object.prototype.toObject);
    

    您必须接收properties 参数并将其传递给toObject

    【讨论】:

    • 它绝对完美,非常感谢伙伴。我已经测试过它工作正常。
    【解决方案2】:

    下面是添加自定义属性并将它们保存为 JSON 序列化的代码,用于画布上的任何对象。 (我使用了标准的 javascript 对象属性,但它适用于我)

    canvas.myImages = {};
    fabric.Image.fromURL('SOME-IMAGE-URL.jpg', function(img) {
          canvas.myImages.push(img);
          var i = canvas.myImages.length-1;
    
          canvas.myImages[i].ID = 1;  // add your custom attributes
          canvas.myImages[i].GeoLocation = [40, 40];
    
          canvas.add(canvas.myImages[i]);
          canvas.renderAll();
    });
    

    然后在对象序列化中包含自定义属性。

    // Save additional attributes in Serialization
    fabric.Object.prototype.toObject = (function (toObject) {
        return function () {
            return fabric.util.object.extend(toObject.call(this), {
                textID: this.textID
            });
        };
    })(fabric.Object.prototype.toObject);
    
    // Test Serialization
    var json = JSON.stringify(canvas.toDatalessJSON());
    console.log(json);
    
    canvas.clear();
    
    // and load everything from the same json
    canvas.loadFromDatalessJSON(json, function() {
        // making sure to render canvas at the end
        canvas.renderAll();
    }
    

    【讨论】:

      猜你喜欢
      • 2015-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      • 1970-01-01
      相关资源
      最近更新 更多