简体   繁体   中英

How do I read and convert a local SVG file into text?

I'm trying to find a way to convert a local (server) SVG file to text or an object. I've seen some solutions but they're mostly about the SVG being displayed inline on a page. I want to retrieve it from a disk and directly access its data.

The goal is to expose the information inside the SVG file such as the path element. I want to read this information and further process it.

Example

<svg height="210" width="400"><path d="M150 0 L75 200 L225 200 Z" /><path d="M150 0 L75 200 L225 200 Z" /></svg>

I am trying to figure a way to retrieve the path data from SVG files like the one included above, programmatically. Loop through all the path elements and get the data behind "d". Currently using Vue and working locally.

You should be able to use the Fetch and DOMParser APIs.

Something like (but not necessarily exactly) the following:

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"))
}

This is writed typescript, convert to anything!

   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");
          });
      };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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