Как проанализировать SVG-данные из URL-адреса с помощью JSON.parse () в JavaScript? - PullRequest
0 голосов
/ 26 июня 2019

Я просто хочу проанализировать некоторые данные этого svg по этому URL: http://colorillo.com/bxys.inline.svg Когда я просматриваю источник страницы.Я хотел бы проанализировать данные points и stroke и отправить их в консоль Google с помощью console.log ()

Мой код показан ниже, это то, что я пытался сделать, но мне не повезлозаставить его печатать в консоли.

    var url = new url("http://colorillo.com/bxys.inline.svg");

    url = function(e) {
    var obj = JSON.parse(e.data);
    var points = JSON.stringify(obj.points)
    var stroke = JSON.stringify(obj.stroke)
    }

    console.log(points)
    console.log(stroke)

1 Ответ

1 голос
/ 26 июня 2019

Существуют различные проблемы с вашим кодом, например, определение url дважды.Вы, вероятно, хотите использовать fetch API, чтобы получить его.Вам нужно будет запустить свой код на colorillo.com или переназначить файл на вашем собственном сервере, потому что они не настроили CORS, чтобы позволить вам получить доступ к файлу с другого сайта.

SVG - это диалектXML, а не JSON.Вам нужно использовать DOMParser:

// Create request to fetch the SVG file.
xhr=new XMLHttpRequest();
// Tell the request where the file is.
xhr.open("GET", "http://colorillo.com/bxys.inline.svg");
// Add event handler to process the file once it's been fetched.
xhr.addEventListener("load", function() {
  // Once the text is available, create an XML parser
  // and parse the text as an SVG image.
  const xmlDoc = new DOMParser().parseFromString(
    this.responseText.trim(), 
    "image/svg+xml"
  );
  // xmlDoc.getElements() returns something Array-like, but not an Array.
  // This turns it into an Array.
  const polylines = Array.from(xmlDoc.getElementsByTagName('polyline'));
  console.log(polylines.map(
    pl => [
      // Parses each 'points' attribute into an array of pairs of numbers
      pl.getAttribute('points').split(' ').map(
        pair => pair.split(',').map(x=>+x)
      ),
      // Various stroke information

      // Convert rgb(R,G,B) to #RRGGBB
      // Leading hash, then pull out the digits with a regex
      '#' + pl.style.stroke.match(/rgb\((\d*), (\d*), (\d*)\)/)
        // Throw away everything but the digits
        .slice(1,4)
        // Convert to a number, render in hex, uppercase, pad with 0s
        .map(x=>(+x).toString(16).toUpperCase().padStart(2,'0'))
        // Concatenate the hex digits
        .join(''),
      +pl.style.strokeWidth,
      pl.style.strokeLinejoin,
      pl.style.strokeLinecap
    ]
  ));
});
xhr.send();
...