Hi

I was wondering how to do "for" loop in svg, i need it to do something like this:

500 rectangles i rows, simple black rectangels.

I did this with Canvas but i dont know how to make it with svg. Could you help me with this??

Dani AI

Generated

SVG markup does not have control structures like loops, but you can generate repeated elements at runtime with JavaScript. The main gotcha is timing: create the <rect> elements after the SVG is in the DOM. A simple way is to wait for DOMContentLoaded, then build a grid and append it in one batch for better performance.

<script>
document.addEventListener('DOMContentLoaded', () => {
  const svg = document.getElementById('svgOne');

  const cols = 25, rows = 20;   // 25 * 20 = 500 rectangles
  const size = 10, gap = 2;     // cell size and spacing
  const ns = 'http://www.w3.org/2000/svg';
  const frag = document.createDocumentFragment();

  for (let r = 0; r < rows; r++) {
    for (let c = 0; c < cols; c++) {
      const rect = document.createElementNS(ns, 'rect');
      rect.setAttribute('x', c * (size + gap));
      rect.setAttribute('y', r * (size + gap));
      rect.setAttribute('width', size);
      rect.setAttribute('height', size);
      rect.setAttribute('fill', '#000');
      frag.appendChild(rect);
    }
  }
  svg.appendChild(frag);
});
</script>

If you only need a tiled look (not 500 distinct nodes), consider an SVG pattern instead, which paints an area using a single definition and is much lighter on the DOM. See the MDN docs for <pattern>. For reusing a predefined shape at multiple positions, define a <symbol> once and place copies with <use> (prefer the href attribute per SVG 2): MDN <use>. Creating SVG elements with the proper namespace is covered here: MDN createElementNS.

Recommended Answers

All 11 Replies

I don't think SVG supports loops. What you can do is reuse an element, but you still need to add a tag for every one you need. Unless of course you programmatically generate your SVG.

Yeah SVG dont support loops but i was thinking about using javasript with svg and then use it to do some kind of loop but dont know how. Any ideas?? I am doing SVG in html file.

Can you show what you have?

Well i have nothing i mean i know how to do rectangle in SVG but dont know how to do rest. I mean its dont have to be loop. But how to draw 100 rectangles using SVG without 100 lines of code??

You can't.

hmm i know it is posible. Will have to look more. Maybe someone else have idea??

you can use a trick something like this:-

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">  
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="128px" height="128px" viewBox="0 0 16 16">

    <g>
        <animateTransform attributeName="transform" type="rotate" 
           values="0 8 8; 45 8 8; 90 8 8; 135 8 8; 180 8 8; 225 8 8; 270 8 8; 315 8 8" 
           dur="8s" calcMode="discrete" repeatCount="indefinite" />

        <rect fill="#404040" x="7.062" y="3.625" width="1.875" height="8.75"/>
    </g>


</svg>

This is for rotation,it actually is not a loop but animation effect.

For loop you have to use javascript,dynamically create svg element and then use loop on it. http://stackoverflow.com/questions/12786797/how-to-draw-rectangles-dynamically-in-svg

Thx for your answer. I was looking for something like this.

But i cant get it work. Can some one tell me why this code dont works??

<html>
<head>
<script type="text/javascript">

var svgns = "http://www.w3.org/2000/svg";
function rectan()
{
for (var i = 0; i < 100; i++) {
    var x = Math.random() * 5000,
        y = Math.random() * 3000;

    var rect = document.createElementNS(svgns, 'rect');
    rect.setAttributeNS(null, 'x', x);
    rect.setAttributeNS(null, 'y', y);
    rect.setAttributeNS(null, 'height', '50');
    rect.setAttributeNS(null, 'width', '50');
    rect.setAttributeNS(null, 'fill', '#'+Math.round(0xffffff * Math.random()).toString(16));
    document.getElementById('svgOne').appendChild(rect);
}
}
</script>
</head>
<body onload="rectan"();">

<svg id="svgOne" xmlns="http://www.w3.org/2000/svg" width="5000" height="3000"> 
<rect x="50" y="50"
            width="50" height="50"
            fill="black" 
            />
</svg>
</body>
</html>

It should genereate rectranles. but all it does is one rectangle from svg section.

Line 23 has a double quote too much.

You have right. Thx for your answer. But still it dont show the random rectangles just one from svg section. What else can be wrong??

Hello, for me it works if I put the script at the end of the body and then I call the function:

<html>
<head>

</head>
<body>

<svg id="svgOne" xmlns="http://www.w3.org/2000/svg" width="5000" height="3000"> 
<rect x="50" y="50"
            width="50" height="50"
            fill="black" 
            ></rect>
</svg>
<script type="text/javascript">

var svgns = "http://www.w3.org/2000/svg";
function rectan()
{
for (var i = 0; i < 100; i++) {
    var x = Math.random() * 5000,
        y = Math.random() * 3000;

    var rect = document.createElementNS(svgns, 'rect');
    rect.setAttributeNS(null, 'x', x);
    rect.setAttributeNS(null, 'y', y);
    rect.setAttributeNS(null, 'height', '50');
    rect.setAttributeNS(null, 'width', '50');
    rect.setAttributeNS(null, 'fill', '#'+Math.round(0xffffff * Math.random()).toString(16));
    document.getElementById('svgOne').appendChild(rect);
}

}
rectan();
</script>
</body>
</html>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.