Trying to do a for loop to draw svg

I was just starting to learn SVG and wanted to try making a for loop to draw a lot of circles in my html. Can this be done, am I trying to do this, or is this what I am trying to make impossible?

<html>
<body>

<h1>My first SVG for loop</h1>

<script type="text/javascript">

    var circlex = 50; 
    var circley = 50;

    for (var i = 0; i < 100; i++) {

    <svg width="100" height="100">
         <circle cx="circlex + 1" cy="circley + 1" r="40" stroke="green" stroke-width="4" fill="yellow" />
    </svg>
    };

</script>

</body>
</html>
+4
source share
2 answers

So close so far

You cannot put html code directly in javascript (that would be cool)
The way javascript adds new elements is dom manipulation. So let's skip the code:

  • First created an empty svg document with xmlns (just set xmlns = "http://www.w3.org/2000/svg" works 99% of the time) and we need an identifier to select the item.
  • svg javascript: document.getElementById( "svg_circles" ). , , .
  • foorloop: : var circle = document.createElementNS(NS, "" ); Ns 1. http://www.w3.org/2000/svg , , , .
  • : : cx and c y with.setAttribute() you could self try to position them differently. I also set the size r` ( , )

  • , javascript , . : svgCircle ( svg).appendChild() svg. : svgCircle.appendChild(circle); circle - svg.

document.addEventListener("DOMContentLoaded", function(event) {
  var circlex = 0;
  var circley = 0;

  var svgCircle = document.getElementById("svg_circles");
  var NS = "http://www.w3.org/2000/svg";
  for (var i = 0; i < 100; i++) {
    var circle = document.createElementNS(NS, "circle");
    console.log(circle);
    circle.setAttribute("cx", circlex + i);
    circle.setAttribute("cy", circley + i);
    circle.setAttribute("r", 10);
    circle.setAttribute("fill", "rgb(" + Math.floor(Math.random() * 255) + "," + Math.floor(Math.random() * 255) + "," + Math.floor(Math.random() * 255) + ")");
    svgCircle.appendChild(circle);
  };
});
<svg id="svg_circles" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
</svg>
Hide result
+1

, , js-. , , ..net mvc, svg. js dom, dom. : https://jsfiddle.net/9c7ro6x3/1/

  var circlex = 50;
  var circley = 50;

  var svg = document.createElementNS("http://www.w3.org/2000/svg", 'svg');
  for (var i = 0; i < 100; i++) {
   circlex = circlex + 1;
   circley = circley + 1;

   var circle = document.createElementNS("http://www.w3.org/2000/svg", 'circle');
   circle.setAttribute("cx", circlex);
   circle.setAttribute("cy", circley);
   circle.setAttribute("r", "40");
   circle.setAttribute("stroke", "green");
   circle.setAttribute("strokeWidth", 4);
   circle.setAttribute("fill", "yellow");
   svg.appendChild(circle);
};
document.body.appendChild(svg);
+3

Source: https://habr.com/ru/post/1619351/


All Articles