2

recently i have been learning the Fourier transform and Fourier series. I was inspired by 3Blue1Brown's video and i started working on my own program of the circles drawing machine which he has represented in his video. Sadly python's graphic interface is very bad so i decided to use p5.js. That went very well but the only problem is that i can only test my program on parametric functions e.g f(t) = (3sin(t) , cos(5t)). i spent the last entire week searching how can i convert a .svg file which contains <path> to array of 2D points so i can test the program on but i can't find topics relates to that. Could someone explain to me how can i do that? or maybe i might miss something about how svg files fit in javacript because i actually doesn't know so much about html and svg (plan to learn it soon).

i have tried that method :

  var svg = fetch("https://s3-us-west-2.amazonaws.com/s.cdpn.io/106114/tiger.svg")
    .then(response => response.text())
    .then(text => (new DOMParser()).parseFromString(text, "image/svg+xml"))
    .then(svg => svg.documentElement);

  var path = svg.querySelector("path")

but it throws an error :

Uncaught TypeError: svg.querySelector is not a function
at setup (Sketch.js:41)
at m.<anonymous> (p5.min.js:3)
at m.<anonymous> (p5.min.js:3)
at new m (p5.min.js:3)
at n (p5.min.js:3)

i checked and turns out that svg is a null. Can someone help me with that thing? thanks!

Itay2924
  • 21
  • 3

2 Answers2

1
 var svg = fetch("https://s3-us-west-2.amazonaws.com/s.cdpn.io/106114/tiger.svg")
    .then(response => response.text())
    .then(text => (new DOMParser()).parseFromString(text, "image/svg+xml"))
    .then(parsedSvg => {
      // In here you can do stuff with the DOM parsed from the above promise chain
      var path = parsedSvg.querySelector("path")
      console.log(path)
    });

// Out here, svg just refers to an unresolved promise 
// Uncaught TypeError: svg.querySelector is not a function 
// var path = svg.querySelector("path")

Codepen

ksav
  • 20,015
  • 6
  • 46
  • 66
0

It looks as though you are trying to access the innards of an SVG using JavaScript.

SVG has it's own DOM, separate from HTML. The SVG Dom is referenced via Name Space.

Here is an example of creating an SVG using JavaScript:

var NS="http://www.w3.org/2000/svg";
var svg=document.createElementNS(NS,"svg");
svg.width=32;
svg.height=32;
svg.setAttribute('viewBox', '-4 -5 32 32');
svg.setAttribute("class", "svg-circle");
var circle = document.createElementNS("http://www.w3.org/2000/svg", "circle");
circle.setAttribute("cx", "12");
circle.setAttribute("cy", "12");
circle.setAttribute("r", "13");
circle.setAttributeNS(null, "stroke-width", "2");
const circleBox = document.createElement("div");
circleBox.classList.add("svg-circle", "circleBox");
document.body.appendChild(circleBox);
CWebba1
  • 27
  • 6