简体   繁体   English

如何改变svg圈的颜色

[英]How to change color of svg circle

How to change color of svg circle genereted by for loop. 如何改变for循环所产生的svg圈的颜色。

Im trying to change color of circle by right click and then save it into array. 我试图通过右键单击更改圆的颜色,然后将其保存到数组中。

 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> 

In order to make it work I've added an id to every point since you have this line of code: circle.setAttribute('id', points[i]["id"]); 为了使它工作,我已经为每一点添加了一个id ,因为你有这行代码: circle.setAttribute('id', points[i]["id"]);

Also I've replaced var circle with let circle 我也用let circle替换了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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM