如何在JavaScript中采样.svg文件?

问题描述 投票:0回答:2

最近,我一直在学习傅立叶变换和傅立叶级数。 3Blue1Brown的video启发了我,我开始研究自己在他的视频中表示的圆形绘图机程序。可悲的是python的图形界面非常糟糕,所以我决定使用p5.js。进行得很好,但是唯一的问题是我只能在参数函数(例如f(t) = (3sin(t) , cos(5t)))上测试程序。我花了整整一周的时间搜索如何将包含<path>的.svg文件转换为2D点数组,以便可以测试该程序,但找不到与此相关的主题。有人可以向我解释我该怎么做吗?也许我可能会错过一些有关svg文件如何适合javacript的信息,因为我实际上对html和svg并不了解太多(计划很快学习)。

我尝试过该方法:

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

但是它抛出一个错误:

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已检查,结果证明svg为空。有人可以帮我做那件事吗?谢谢!

javascript svg p5.js dft
2个回答
0
投票

似乎您正在尝试使用JavaScript访问SVG的内部。

SVG具有它自己的DOM,与HTML分开。 SVG Dom通过名称空间引用。

这里是使用JavaScript创建SVG的示例:

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

0
投票
 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

© www.soinside.com 2019 - 2024. All rights reserved.