user2324169
user2324169

Reputation:

creating circles with svg and javascript

(UPDATED) I'm having some issues regarding svg and javascript. What I want to create is a series of circles on top of one another, with their radius (r) values increasing by one each time the loop goes round, so that it creates some sort of a pattern. Here is what I have so far(for loop values are from another forum post, I would rather do it with a while loop that would execute 10 times) -

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Dynamic SVG!</title>
</head>
<defs>
    <svg height="10000" width="10000" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
         <circle id="cir1" cx="300" cy="300" r="40" stroke="yellow" stroke-width="" fill="none"/>
</svg>
</defs>
<script>
   var svgns = "http://www.w3.org/2000/svg";
   for (var x = 0; x < 5000; x += 50) {
       for (var y = 0; y < 3000; y += 50) {
          var circle = document.createElementNS(svgns, 'circle');
          circle.setAttributeNS(null, 'x', x);
          circle.setAttributeNS(null, 'y', y);
          circle.setAttributeNS(null, 'height', '50');
          circle.setAttributeNS(null, 'width', '50');
          document.getElementById('cir1').appendChild(circle);
        }
   }
</script>
<body>
</body>
</html>

Any help out there? Thanks.

Upvotes: 7

Views: 26130

Answers (1)

Sirko
Sirko

Reputation: 74036

Ok, so this is, what I had to fix in order to get your code working:

  • You append to the circle element, but should append to the svg-container. A circle element has no child elements.
  • You did not set any styles for the circles, so they were transparent.
  • The coordinates in a circle element are called cx and cy instead of x and y.
  • The <defs> element should be a child of the <svg> element. Also everything within it wont be rendered.

JavaScript

var svgns = "http://www.w3.org/2000/svg",
    container = document.getElementById( 'cont' );
for (var x = 0; x < 500; x += 50) {
    for (var y = 0; y < 300; y += 50) {
        var circle = document.createElementNS(svgns, 'circle');
        circle.setAttributeNS(null, 'cx', x);
        circle.setAttributeNS(null, 'cy', y);
        circle.setAttributeNS(null, 'r', 50);
        circle.setAttributeNS(null, 'style', 'fill: none; stroke: blue; stroke-width: 1px;' );
        container.appendChild(circle);
    }
}

HTML

<svg id="cont" height="1000" width="1000" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <circle id="cir1" cx="300" cy="300" r="40" stroke="yellow" stroke-width="" fill="none" />
</svg>

Example Fiddle

I also adjusted your sizes as for a mere test, they were quite big.

Upvotes: 22

Related Questions