【问题标题】:Exporting custom properties from fabricjs objects to SVG将自定义属性从 fabricjs 对象导出到 SVG
【发布时间】:2017-03-23 02:11:59
【问题描述】:

我有一个添加了自定义属性的图像对象。 对对象进行字符串化时,我可以看到该属性在那里,但是当我使用 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()));

};

【问题讨论】:

  • 也许@kangax 可以对此有所了解? :)

标签: svg fabricjs


【解决方案1】:
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/

【讨论】:

  • 不,这不起作用。查看 svg 源,我找不到值为 test 的属性名称。 svg 源与我的小提琴中的相同。
【解决方案2】:

您可以像这样覆盖现有的 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)

【讨论】:

    猜你喜欢
    • 2015-07-31
    • 2019-03-09
    • 2019-06-02
    • 2018-04-20
    • 2015-08-09
    • 2018-11-28
    • 2016-02-17
    • 2017-11-30
    • 2016-04-02
    相关资源
    最近更新 更多