webpack 如何读取本地SVG文件并将其转换为文本?

toiithl6  于 2023-01-05  发布在  Webpack
关注(0)|答案(2)|浏览(188)

我试图找到一种方法来将本地(服务器)SVG文件转换为文本或对象。我见过一些解决方案,但它们大多是关于SVG在页面上内联显示的。我想从磁盘中检索它并直接访问它的数据。
我们的目标是公开SVG文件中的信息,比如path元素,我想读取这些信息并进一步处理它。
示例
第一个月
我试图找到一种从SVG文件中检索路径数据的方法,就像上面包含的那样,通过编程。循环所有的路径元素并获得“d”后面的数据。目前使用Vue并在本地工作。

uwopmtnx

uwopmtnx1#

您应该能够使用FetchDOMParser API。
类似于(但不一定完全)以下内容:

function getAndModifySVG(url) {
  return fetch(url)
            // Get SVG response as text
            .then(response => response.text())
            // Parse to a DOM tree using DOMParser
            .then(str => (new window.DOMParser()).parseFromString(str, "text/xml"))
            // Find path with id="myPath" and return the d attribute
            .then(data => data.getElementById("myPath").getAttribute("d"))
}
pw136qt2

pw136qt22#

这是手写的 typescript ,转换成任何东西!

const loadSvg = (url: string) => {
        return fetch(url)
          .then(function (response) {
            console.log(response);
            return response.text();
          })
          .then(function (raw) {
            return new window.DOMParser().parseFromString(raw, "image/svg+xml");
          });
      };

相关问题