【问题标题】:Custom attributes lost after applying JSON.stringify on fabricjs object在 fabricjs 对象上应用 JSON.stringify 后自定义属性丢失
【发布时间】:2021-06-12 13:27:48
【问题描述】:

我正在向我的织物对象添加自定义属性,如下所示,它可以正常工作,但是当使用 JSON.stringify 将对象转换为字符串时,它不会转换我添加的属性

var customcanva = new fabric.Canvas('c');

// my text object with custom attribute
text = new fabric.IText('Tap and Type', {
    attr0: 'value 0',
});

// with another custom attribute
text.attr1 = "value 1";

// object showing fine as json object 
console.log(text);

// stringified object doesn't have all attributes including my added ones
console.log(JSON.stringify(text));

我这样做是为了可以通过 ajax 请求发送我选择的对象。如何使我的属性保持不变?

【问题讨论】:

    标签: javascript json fabricjs stringify


    【解决方案1】:

    当使用自定义属性序列化 FabricJS 对象时,toJSON() 方法接受附加属性数组。

    var text = new fabric.IText('Tap and Type');
        text.attr1 = 'red';
        text.attr2 = 'blue';
    
    //pass an array of attribute names to the toJSON method
    var json = text.toJSON(['attr1', 'attr2']);
    
    //the output can then be stringified
    var jsonString = JSON.stringify(json);
    

    请参阅此处获取文档: http://fabricjs.com/docs/fabric.Object.html#toJSON

    【讨论】:

      【解决方案2】:

      我找到了解决方案,这就是我所做的。我将我的织物对象转换为一个新的 json 变量并将我的属性添加到它,如下所示:

      
      text = new fabric.IText('Tap and Type');
      
      // my new object
      var newtext = text.toJSON();
      
      // adding my attribute
      newtext.attr1 = "value 1";
      
      // object showing fine as json object 
      console.log(newtext);
      
      // stringified object showing with my added attributes
      console.log(JSON.stringify(newtext));
      
      

      【讨论】:

        猜你喜欢
        • 2018-04-20
        • 2015-07-31
        • 2019-12-11
        • 1970-01-01
        • 2017-03-23
        • 2018-02-23
        • 1970-01-01
        • 2016-12-13
        • 1970-01-01
        相关资源
        最近更新 更多