如何为fabricjs对象添加名称?

时间:2016-06-24 08:31:12

标签: javascript canvas fabricjs

为了按名称获取fabricjs画布图像,我需要为此iamge设置唯一的id或名称。我创建了一个新课程fabric.NamedImage 这就是我的表现。

  fabric.NamedImage = fabric.util.createClass(fabric.Image, {

  type: 'nameimage',

  initialize: function (element, options) {
      this.callSuper('initialize', element, options);
      options && this.set('name', options.name);
  },

  toObject: function () {
      return fabric.util.object.extend(this.callSuper('toObject'), { name: this.name });
  },

  _render: function (ctx) {
      this.callSuper('_render', ctx);
  }}); 

和fromObject

 fabric.NamedImage.fromObject = function (object, callback) {
      fabric.util.loadImage(object.src, function (img) {
          var instance = new fabric.NamedImage(img, object);
          callback && callback(instance);
      });
  };
  fabric.NamedImage.async = true;

但是当我因为某些原因尝试加载画布loadFromJSON时,我一直收到错误

cannot read property 'async' of undefined

以下是我尝试加载JSON

的代码
for (i = 0; i <= canvas.length; i++) {
                    JSON.parse(imageQuery[i]);
                canvas[i].loadFromJSON(imageQuery[i]);
                        canvas[i].renderAll();
                        console.log(' this is a callback. invoked when canvas is loaded!xxx ');              
            }

我已经读过了 cannot read property 'async' of undifinedsave canvas to server with custom attribute

有没有办法按名称获取对象?

3 个答案:

答案 0 :(得分:0)

Plesae将您班级的类型属性更改为“namedImage”&#39;它应该去。

答案 1 :(得分:0)

您可以使用下面给出的代码将自定义属性添加到结构js中的不同对象:

obj.toObject = (function (toObject) {
    return function () {
        return fabric.util.object.extend(toObject.call(this),{
            id : value
        });
    };
})(obj.toObject);

这里obj是您创建的canvas对象,id是我们要添加到此对象的自定义属性。 假设您已经以json文件的形式保存了画布。所以在使用json.stringify时请考虑以下代码:

json_data = JSON.stringify(self.canvas.toJSON(['attribute1', 
'attrubute2']));

方括号中包含所有自定义属性。稍后当您使用loadfromjson时,将自动包含所有自定义属性。希望它会奏效。祝你有美好的一天!!

答案 2 :(得分:0)

根据官方文档

var rect = new fabric.Rect();

rect.toObject = (function(toObject) {
  return function() {
    return fabric.util.object.extend(toObject.call(this), {
      name: this.name
    });
  };
})(rect.toObject);

canvas.add(rect);

rect.name = 'trololo';

console.log(JSON.stringify(canvas));

,记录的输出将为

'{"objects":[{"type":"rect","left":0,"top":0,"width":0,"height":0,"fill":"rgb(0,0,0)","overlayFill":null,"stroke":null,"strokeWidth":1,"strokeDashArray":null,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"selectable":true,"hasControls":true,"hasBorders":true,"hasRotatingPoint":false,"transparentCorners":true,"perPixelTargetFind":false,"rx":0,"ry":0,"name":"trololo"}],"background":"rgba(0, 0, 0, 0)"}'

请参阅此http://fabricjs.com/fabric-intro-part-3 干杯!