Luke Snowden
Luke Snowden

Reputation: 4196

Importing SVG in svg.js

I have created a little sandbox to test this out but according to the docs I should be able to import an SVG using svg.js using https://playcode.io/1024624

mounted() {
  this.$nextTick(() => {
    if(this.svg) {
      this.paper = SVG(this.svg).addTo('#paper');
    } else {
      this.paper = SVG('paper');
    }
  });
}

If you look in the console it throws an error so that can't be the correct way of doing it. I have managed to import using the following https://playcode.io/1024624?v=2

mounted() {
  this.$nextTick(() => {
    if(this.svg) {
      this.paper = SVG('paper');
      this.paper.svg(this.svg, true);
    } else {
      this.paper = SVG('paper');
    }
  });
}

But if you inspect the SVG it inserts the SVG into a SVG which means every time it is saved and reloaded the size of the image will get bigger and there will be multiple elements with the same ID which I believe is the reason why I cant query the elements correctly.

Any help is appreciated.

Upvotes: 0

Views: 109

Answers (1)

Luke Snowden
Luke Snowden

Reputation: 4196

I have tried everything to get this to import the SVG as one but I don't think it's possible. I have however figured out a solution which does the above. Instead of passing the SVG as one to the sever to save and then trying to reload it, I send over all the direct descendants and store them in a json format. I then on load loop through all the children and add them back to a fresh instance of SVG.

Save:

...
elements: this.paper.children().forEach(child => {
  return {
    elm: child.svg(),
    id: child.node.id
  }
});
...

Load:

$children.forEach(child => {
  this.paper.svg(child.elm);
});

Upvotes: 0

Related Questions