简体   繁体   English

Fabric JS将ID分配给导入的SVG

[英]Fabric js assign id to imported svg

I'm trying to assign an id to my svgs when i load them because during different times i load different things so the order is not always the same. 我尝试在加载svg时为其分配一个ID,因为在不同时间加载不同的东西,因此顺序并不总是相同。

var svgImages = ['textarea-max', 'textarea-min', 'cutout-test']

for (var i = 0; i < svgImages.length; i++) {
  fabric.loadSVGFromURL("/" + svgImages[i] + ".svg", function(objects, options) {
    objects.svgUid = svgImages[i]; (this was just a test)
    var obj = fabric.util.groupSVGElements(objects, options);
    canvas.add(obj);
    canvas.renderAll();
  });
};

So the first two ids are made automatically for some reason (textarea-max and textarea-min but the last is just 1). 因此,由于某些原因(textarea-max和textarea-min,但最后一个仅为1)会自动创建前两个ID。 They were created at the same time by me in the same way. 它们是由我以相同的方式在同一时间创建的。 Just seems odd that it the case. 情况似乎很奇怪。 Any ideas would be a help at this point. 此时任何想法都将有所帮助。

var svgImages = ['textarea-max', 'textarea-min', 'cutout-test']

for (var i = 0; i < svgImages.length; i++) {
  (function(i) {
    fabric.loadSVGFromURL("/" + svgImages[i] + ".svg", function(objects, options) {
      var obj = fabric.util.groupSVGElements(objects, options);
      obj.svgUid = svgImages[i];
      canvas.add(obj);
      canvas.calcOffset();
      canvas.renderAll();
    });
  })(i);
};

loadSVGFromURL takes anonymous function there i value will not set as expected. loadSVGFromURL需要匿名函数,而我的值将不会按预期设置。 so make another function and pass i value in that scope you can get exact i value and set svgUid to obj created from groupSVGElements then add to canvas. 因此,使另一个函数并在该范围内传递i值,您可以获得确切的i值并将svgUid设置为从groupSVGElements创建的obj,然后添加到画布。

ES6 ES6

const svgImages = ['textarea-max', 'textarea-min', 'cutout-test'];

for (let i = 0; i < svgImages.length; i++) {
  fabric.loadSVGFromURL(`/${svgImages[i]}.svg`, (objects, options) => {
    const obj = fabric.util.groupSVGElements(objects, options);
    obj.svgUid = svgImages[i];
    canvas.add(obj);
    canvas.calcOffset();
    canvas.renderAll();
  });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM