gpt4 book ai didi

javascript - 如何将 SVGPolyline 的点提取为二维数组

转载 作者:行者123 更新时间:2023-12-02 23:23:52 25 4
gpt4 key购买 nike

我的问题是我的脚本没有按照我希望的方式输出数组数据。

正如您在这里看到的:https://pastebin.com/raw/3AcEs1gc这显示了它当前的输出方式(在 Google 的控制台中)以及我希望它如何输出。

我的代码显示在最底部。我只需要它将“[”添加到数组的最开始,并在其末尾添加“]”我还需要它在每个配对数字后面添加这些内容,并用逗号替换每个配对数字后面的空格。所以它会输出这样的例子 [[200,100],[250,123]] 。&不是这样200, 400 245, 500 <这是目前登录谷歌控制台的方式。

pastebin 链接有更多解释。如果需要更详细的回复。我会尽力解释。

我的代码:

xhr=new XMLHttpRequest();
// Tell the request where the file is.
xhr.open("GET", "http://someurl.com/blahblah.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'));


var Lines = (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,

]
));
console.log(Lines) // Logs the arrays to console.
});
xhr.send();

最佳答案

使用 SVGPolylineElement 中可用的 SVGPointList 接口(interface)提取所有 SVGPoints它包含。然后,您只需将所有这些 SVGPoints xy 属性映射到等效的 [x, y] 数组:

makeSVGPointListIterable();

const polyline = document.querySelector('polyline');
console.log(parsePoints(polyline));

function parsePoints(elem) {
return [...elem.points] // convert to an Array so we can map its content
.map((pt) => [pt.x, pt.y]); // convert to an Array
}






// small monkey patch for Safari
function makeSVGPointListIterable() {
const proto = SVGPointList.prototype;
if (typeof proto[Symbol.iterator] !== 'function') {
proto[Symbol.iterator] = function() {
let current = 0;
return {
next: () => {
const is_done = current === this.numberOfItems;
return {
done: is_done,
value: is_done || this.getItem(current++)
}
}
};
}
}
}
<svg viewBox="0 0 200 100" xmlns="http://www.w3.org/2000/svg">
<!-- even with stoopid new lines in the attribute -->
<polyline points="100,100 150,25 150,75
200,0" fill="none" stroke="black" />
</svg>

关于javascript - 如何将 SVGPolyline 的点提取为二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56825077/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com