Javascript:如何将SVG图像放入数组中

Javascript: How can I put SVG images into an array?

本文关键字:数组 图像 SVG Javascript      更新时间:2023-09-26

假设我有三个圆圈 - 一个红色,一个黄色和一个绿色。

    <svg height="100" width"100"=""> <circle cx="50" cy="50" r="40" stroke = "black" stroke-width = "3" fill="red "></circle> </svg>
    <svg height="100" width"100"=""> <circle cx="50" cy="50" r="40" stroke = "black" stroke-width = "3" fill="yellow"></circle> </svg>  
    <svg height="100" width"100"=""> <circle cx="50" cy="50" r="40" stroke = "black" stroke-width = "3" fill="green"></circle> </svg>

是否可以创建一个包含这 3 个的数组?如果没有,您能否推荐一种可以创建一个包含红色、黄色和绿色三个圆圈的数组的方法?

非常感谢

如果你在数组中需要它们,请先获取它们的父元素。让我们称之为svgParent然后这样做。

var svgArr = Array.prototype.slice.call(svgParent.querySelectorAll("svg"));

您应该将三个 SVG 元素放在一个正确的数组中。我们使用父元素element.querySelectorAll(),因为如果存在其他 svg 元素,我们不想收集这三个元素以外的 svg 元素。

<svg height="100" width="100"> <circle cx="50" cy="50" r="40" stroke = "black" stroke-width = "3" fill="red "></circle> </svg>
    <svg height="100" width="100"> <circle cx="50" cy="50" r="40" stroke = "black" stroke-width = "3" fill="yellow"></circle> </svg>  
    <svg height="100" width="100"> <circle cx="50" cy="50" r="40" stroke = "black" stroke-width = "3" fill="green"></circle> </svg>

JS代码

var svgArray = document.querySelectorAll('svg');
console.log(svgArray[0]); // svgArray[0] is red circle

https://jsfiddle.net/b9mysaew/演示(检查控制台)

可以使用

document.querySelectorAll('svg');document.getElementsByTagName('svg')将所有svg元素放在类似对象的数组中。

document.querySelectorAll()将返回一个NodeList

document.getElementsByTagName('')会返回HTMLCollection

1- 创建父 SVG 元素

2-将数据绑定到svg并回车()

var svg = d3.select("body").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom + 20);
var circles = svg.selectAll(".month")
    .data(eachcircle);
//loop from 0 to eachcircle.length
circlesdata(eachcircle).append("circle")
    .attr("cx", function(d,i) { return d[["x"];}) 
    .attr("cy", function(d,i) { return d["y"];})
    .attr("r", function (d) { return d["r"]; })
    .style("fill", function(d) { return d["color"]; });