如何解决在fabricjs对象上应用JSON.stringify后自定义属性丢失
我正在向我的结构对象添加自定义属性,如下所示,它可以正常工作,但是当使用 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请求发送我选择的对象。如何让我的属性持久化?
解决方法
使用自定义属性序列化 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
,我在这里找到了解决方案。我将我的结构对象转换为一个新的 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));
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。