如何更改for循环生成的svg圆的颜色。
我试图通过右键单击更改圆形的颜色,然后将其保存到数组中。
var svgInfo = 'http://www.w3.org/2000/svg';
var customSvg = document.querySelector('svg');
var points = [
{x: 5, y: 5},
{x: 50, y: 50},
];
var selected = [];
for (var i = 0; i < points.length; ++i) {
var circle = document.createElementNS(svgInfo, 'circle');
circle.setAttribute('cx', points[i]["x"]);
circle.setAttribute('cy', points[i]["y"]);
circle.setAttribute('stroke', 'red');
circle.setAttribute('stroke-width', 5);
circle.setAttribute('r', 5);
circle.setAttribute('fill', 'green');
circle.setAttribute('fill-opacity', 0);
circle.setAttribute('id', points[i]["id"]);
circle.addEventListener('contextmenu', function (event) {
let s = 0;
circle.setAttribute('stroke', 'green');
selected[s] = {id: circle.id, x: circle.cx, y: circle.cy};
s++;
event.preventDefault();
});
customSvg.appendChild(circle);
}
<svg></svg>
答案 0 :(得分:0)
为了使其正常工作,我已经在每一点上添加了id
,因为您拥有以下代码行:circle.setAttribute('id', points[i]["id"]);
我也将var circle
替换为let circle
var svgInfo = 'http://www.w3.org/2000/svg';
var customSvg = document.querySelector('svg');
var points = [
{x: 5, y: 5,id:"a"},
{x: 50, y: 50,id:"b"},
];
var selected = [];
for (var i = 0; i < points.length; i++) {
let circle = document.createElementNS(svgInfo, 'circle');
circle.setAttribute('cx', points[i]["x"]);
circle.setAttribute('cy', points[i]["y"]);
circle.setAttribute('stroke', 'red');
circle.setAttribute('stroke-width', 5);
circle.setAttribute('r', 5);
circle.setAttribute('fill', 'green');
circle.setAttribute('fill-opacity', 0);
circle.setAttribute('id', points[i]["id"]);
circle.addEventListener('contextmenu', function (event) {console.log(circle.id)
let s = 0;
circle.setAttribute('stroke', 'green');
selected[s] = {id: circle.id, x: circle.cx, y: circle.cy};
s++;
event.preventDefault();
});
customSvg.appendChild(circle);
}
svg {
border: 1px solid;
}
<svg></svg>