Search code examples
javascripttypescriptsvggridvector-graphics

SVG: generate a grid with random fill colour for each cell/rect?


Is there a way to generate an SVG grid with specified columns/rows and give each cell a different fill colour?


Solution

  • First you need to think about how to create a random color. A simple solution would be using hsl colors with a random hue value.

    function randomColor(){
    return `hsl(${ Math.floor(Math.random()* 360)}, 100%, 50%)`
    }
    

    You can enhance the function by using also random saturation, and lightness.

    Next you need a function to create a rectangle - i.e the cell of the grid. This is a function that createsa rect. The object o has all the attributes needed for the rect.

    A double loop will create all the cels for the grid.

    You can change the size of the cells by changing the width and the height (w and h vars). You can change the size of the grid by adding a width attribute to the svg element.

    const SVG_NS = 'http://www.w3.org/2000/svg';
    //size (width and height) of the cell
    let w = 10,h=10;
    
    
    //generate the grid
    for(let y = 0; y < 100; y+= h){
    for(let x = 0; x < 100; x+= w){
      let o = {x:x,y:y,width:w,height:h,fill:randomColor()};
      drawRect(o, s)
    }
    }
    
    //function to generate a random color
    function randomColor(){
    return `hsl(${ Math.floor(Math.random()* 360)}, 100%, 50%)`
    }
    
    //function to create a new svg rect
    function drawRect(o, parent) {
      let rect = document.createElementNS(SVG_NS, 'rect');
      for (var name in o) {
        if (o.hasOwnProperty(name)) {
          rect.setAttributeNS(null, name, o[name]);
        }
      }
      parent.appendChild(rect);
      return rect;
    }
    <svg viewBox="0 0 100 100" id="s"></svg>