【问题标题】:Loading External SVG file into SVGJS (Duplicate SVG Tag)将外部 SVG 文件加载到 SVGJS(重复的 SVG 标签)
【发布时间】:2020-05-18 07:02:55
【问题描述】:

我正在尝试将 SVG 文件加载到 svg.js 中。 我的问题是 svg.js 会生成 svg 标签,当我导入我的 svg 时,它会以 2 个 SVG 标签结束,这会导致冲突。

main.js

import Vue from 'vue'
import { SVG } from '@svgdotjs/svg.js';
Vue.prototype.$SVG = SVG;

模板

  <div>
    <button @click="importSVG">import</button>
    <div ref="drawing"></div>
  </div>

  data() {
    return {
      svgFile: require("../assets/cassete.svg")
    };
  },
   importSVG() {
      fetch(this.svgFile)
        .then(res => res.text())
        .then(svg => {
          var tempEl = this.$refs.drawing;
          var draw = this.$SVG()
            .addTo(tempEl)
            .size('100%', '100%');

          draw.svg(svg);
          console.log(svg);


          var parser = new DOMParser();
          var xmlDoc = parser.parseFromString(svg, "application/xml");
          console.log(xmlDoc);
        });
    }

结果归结为 SVG.JS 生成了一个 svg 标签,并且一个已经包含在我的 svg 文件中。

最好的选择是通过 xml 树挑选元素吗?

结果

【问题讨论】:

  • 碰撞是什么意思?
  • @RobertLongson Collisions 例如,它会更改 svgjs 生成的 svg 的属性,而使另一个 svg 标记的属性不受影响,例如。如果我更改大小(宽度和高度),它会在一个 svg 标签(由 svgjs 生成的标签)中更改它,而不是另一个,给我留下一个过大并被剪掉的 svg。
  • 然后给内部 svg 元素的宽度和高度为 100%。

标签: javascript vue.js svg svg.js


【解决方案1】:

您创建一个 SVG,然后再次向其中添加一个 SVG(来自您导入的数据)

您应该直接将导入的 SVG 添加到您的 Div:

  data() {
  return {
    svgFile:     require("../assets/cassete.svg")
  };
},
 importSVG() {
    fetch(this.svgFile)
      .then(res => res.text())
      .then(svg => {
        var tempEl = this.$refs.drawing;
        var draw = svg //this.$SVG()
          .addTo(tempEl)
          .size('100%', '100%');

      //draw.svg(svg);
      console.log(svg);


      var parser = new DOMParser();
      var xmlDoc = parser.parseFromString(svg, "application/xml");
      console.log(xmlDoc);
    });
}

【讨论】:

  • this.$SVG() 是我的 main.js 的原型,Vue.prototype.$SVG = SVG; 我不能不加注释。
  • 您对问题所在的想法是正确的,谢谢。我找到了解决方案。
【解决方案2】:
    importSVG() {
      fetch(this.svgFile)
        .then(res => res.text())
        .then(svg => {
          var tempEl = this.$refs.drawing;

          var draw = this.$SVG(tempEl);
          draw.svg(svg);
        });
    }

正如@Alex L 所说“您应该直接将导入的 SVG 添加到您的 Div”

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-05
    • 1970-01-01
    • 1970-01-01
    • 2015-07-26
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 2014-04-09
    相关资源
    最近更新 更多