将自定义属性从fabricjs对象导出到SVG

时间:2016-11-09 09:53:22

标签: svg fabricjs

我有一个图像对象,我添加了一个自定义属性。 字符串化对象时,我可以看到属性存在,但是当我使用toSVG导出SVG时,自定义属性不在SVG源中。

我希望我的示例中的name属性作为SVG图像xml数据中的自定义属性导出(可以添加多个属性)

这可能吗?

请小提琴:https://jsfiddle.net/Jonah/ujexg46s/

var svgImage = fabric.util.createClass(fabric.Image, {
  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
    });
  }
});

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

function loadImage() {
  var img = new Image();
  img.src = imageSrc;
  img.onload = function() {
    var image = new svgImage(img, {
      name: "test",
      left: 0,
      top: 0
    });
    canvas.add(image);
  }

}

document.getElementById('load-btn').onclick = function() {
  loadImage();
};

document.getElementById('export-btn').onclick = function() {
  canvas.deactivateAll().renderAll();
  console.log(JSON.stringify(canvas));
  window.open('data:image/svg+xml;utf8,' + encodeURIComponent(canvas.toSVG()));

};

2 个答案:

答案 0 :(得分:0)

You can find answer here.
fabric.util.object.extend(fabric.Image.prototype, {
    toObject: function(propertiesToInclude) {
        return fabric.util.object.extend(this.callSuper('toObject', propertiesToInclude), {
            src: this._originalElement.src || this._originalElement._src,
            filters: this.filters.map(function(filterObj) {
                return filterObj && filterObj.toObject();
            }),
            crossOrigin: this.crossOrigin,
            alignX: this.alignX,
            alignY: this.alignY,
            meetOrSlice: this.meetOrSlice,
            name: this.name
        });
    },
});

https://jsfiddle.net/mullainathan/ujexg46s/1/

答案 1 :(得分:0)

您可以像这样覆盖现有的toSVG功能。

var circle = new fabric.Circle ({
          radius: 40,
          left: 50,
          top: 50,
          fill: 'rgb(0,255,0)',
          opacity: 0.5,
          id: 'hello'
    });
    circle.toSVG = (function(toSVG) {
      return function(){
        var svgString = toSVG.call(this);
        var domParser = new DOMParser();
        var doc = domParser.parseFromString(svgString, 'image/svg+xml');
        var parentG = doc.querySelector('path')
        parentG.setAttribute('id', this.id);
        return doc.documentElement.outerHTML;
      }
      })(circle.toSVG)