未创建 json 对象

Not creating json object

我正在玩 fabric js,我似乎也找不到方法 create/view json 对象

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

canvas.add(new fabric.Rect({ 
  left: 100, 
  top: 100, 
  width: 50, 
  height: 50, 
  fill: '#faa', 
  originX: 'left', 
  originY: 'top',
  centeredRotation: true
}));

canvas.add(new fabric.Circle({ 
  left: 300, 
  top: 300, 
  radius: 50, 
  fill: '#9f9', 
  originX: 'left', 
  originY: 'top',
  centeredRotation: true
}));

var w = canvas.toJSON();

http://jsfiddle.net/8t4k1xkc/1/

我也试过JSON.stringify,但将循环结构转换为json错误

您在问题中编写的代码有效,您可以使用 JSON.stringify(w) 将其转换为字符串,但也可以简单地调用 JSON.stringify(canvas) (toJSON 将由 stringify 为您调用).

JSFiddle 上的那个,不是,你调用的是 canvas.toJSON(c),错了,这样你就向结果 JSON 附加了额外的属性,在本例中是相同的 canvas (c,浏览器自动为html元素创建的全局变量id="c"),因此循环结构错误。

official documentation:

toJSON(propertiesToInclude)

Returns JSON representation of canvas

Parameters:

  • propertiesToInclude (Array): Any properties that you might want to additionally include in the output