Create grid patterns with canvas (blocks, diamonds, hex)

While making some experiments with a game, I felt the need to add a grid to the background, after much thinking I decided that canvas should be the “best” solutions for this.

However after creating a simple “square” grid I wanted also hexagons and diamond grids. And this is what I’m presenting here, how to create “blocks, diamonds and hexagon” grids with one convenient javascript class.

See the Pen Create grids by Michael Dobekidis (@netgfx) on CodePen.

The markup (minimal)


<div id="grid" style="z-index: 5;top:40px;position:absolute;"></div>


The Creator script

First we create a function and we name it “grid”, and we create some options inside and some default values.


function grid(type, w, h, totalW, totalH){
  
  var $this = this;
  this.type = type || 'blocks';// blocks, diamonds, hexagons
  this.blockW = w || 25;
  this.blockH = h || 25;
  this.container;
        $('#grid').empty();
  
  this.container = document.createElement('div');
  this.container.style.position = 'absolute';
  this.container.style.width = '100%';
  this.container.style.height = '100%';
  this.container.id = 'gridContainer';
    
  
  var c = document.createElement("canvas");
      c.width  = totalW;
      c.height = totalH;
      
  var totalW = totalW || $(document).width();
  var totalH = totalH || $(document).height();
};

At this point we have “emptied” the container and created a new canvas with some specific properties (width, height, position).

Blocks Grid

Now we will create the “blocks” grid type, first we declare the properties like alpha, stroke color, and line width, and then we begin creating the lines.


if(this.type == 'blocks'){
    
  var mapGridCanvas = c.getContext("2d");
  mapGridCanvas.clearRect(0, 0, c.width, c.height);
  mapGridCanvas.globalAlpha = 1;
  mapGridCanvas.strokeStyle = "#1e1e1e";
  mapGridCanvas.lineWidth = 1;
      mapGridCanvas.beginPath();
      var x = 0;
      var y = 0;
  for(var i = 0;i < Math.round(totalW/blockW); i++){
        
    x = i*blockW;
    y = 0;
    mapGridCanvas.moveTo(x,y);
    mapGridCanvas.lineTo(x,y+totalH);
    
  }
    
  for(var j = 0; j < Math.round(totalH/blockH); j++){
        
    x = 0;
    y = j*blockH;
        
    mapGridCanvas.moveTo(x,y);
    mapGridCanvas.lineTo(x+totalW,y);  
        
  }
    
  mapGridCanvas.stroke();
  this.container.appendChild(c);
  document.getElementById('grid').appendChild(this.container);
    
}

The above code, clears the canvas and runs two “for loops” one for the vertical lines and one for the horizontal ones (of course we could nest those, but I thought this was cleaner)

after the loops end the canvas is stroke (the lines are drawn) and we add the canvas element into the DOM with “appendChild” function.

Diamonds Grid

The snippet that creates a diamond shaped grid


var mapGridCanvas = c.getContext("2d");
  mapGridCanvas.clearRect(0, 0, c.width, c.height);
        mapGridCanvas.globalAlpha = 1;
  mapGridCanvas.strokeStyle = "#1e1e1e";
  mapGridCanvas.lineWidth = 1;
      mapGridCanvas.beginPath();
      var x = 0;
      var y = 0;
        var z = 0;
      var counter = 0;
  for(var i = 0; i < Math.round(totalH/blockH); i++){
      
    var z = counter;
    while(x <= blockW*Math.round(totalW/blockW)){
        
      if(z%2 == 0){
        mapGridCanvas.moveTo( x, y+blockW );
        mapGridCanvas.lineTo( x+blockW, y );
      }
      else{
        mapGridCanvas.moveTo(x,y);
        mapGridCanvas.lineTo(x+blockW, y+blockW);
      }
          
      x += blockW;  
      z += 1;
    }
      
      x = 0;
      y = y + blockW;
      counter += 1;
      
  }
    
  mapGridCanvas.stroke();
  this.container.appendChild(c);
  document.getElementById('grid').appendChild(this.container);

The procedure is the same as the blocks however we now create lines that when odd or not they change orientation, this way we create diamond-like shapes.

Hex Grid

Finally this is the code that creates hexagon grid.
We can have the code inside a function and call it like this:


if(this.type == 'hex'){
    
  var c = drawHexGrid({}, c);
  this.container.appendChild(c);
  document.getElementById('grid').appendChild(this.container);
}

And the actual function that draws the hexes on the grid.


function drawHexGrid(opts,c) {
    
  var alpha     = opts.alpha || 1;
  var color     = opts.color || '#1e1e1e';
  var lineWidth    = opts.lineWidth || 1;
  var radius     = opts.radius || 20;
    
      
  var mapGridCanvas = c.getContext("2d");
        mapGridCanvas.clearRect(0, 0, c.width, c.height);
  mapGridCanvas.globalAlpha = alpha;
  mapGridCanvas.strokeStyle = color;
  mapGridCanvas.lineWidth = lineWidth;
  
  //length of line
  r = radius;
  part = 60;
  hexSize = r*Math.sqrt(3);
  yHexSize = r*Math.sqrt(2.25);
  xHexes = 2000 / hexSize;
  yHexes = 2000 / yHexSize;
  
  mapGridCanvas.beginPath();
  
  //loop through hex "rows" and every other row shift
  for (xGrid=0;xGrid<=xHexes;xGrid++){
       for (yGrid=0;yGrid<=yHexes;yGrid++){
            if (yGrid % 2 == 0) {
                //even row
                shiftX = hexSize/2;
             }
             else {
                //odd row
                shiftX=0;
             }
             for (i=0;i<=6;i++) {
                var a = i * part - 90;
                x = r * Math.cos(a * Math.PI / 180)+xGrid*hexSize+shiftX;
                y = r * Math.sin(a * Math.PI / 180)+yGrid*yHexSize;
                if (i == 0) {
                     mapGridCanvas.moveTo(x,y);
                }
                else {
                    mapGridCanvas.lineTo(x,y);
                }
              }
          }
      }
      mapGridCanvas.stroke();
      
      return c;
  }

This is a much more complicated code but its easy to use, here instead of lines we draw the hex shapes one after the other, and when odd we shift the position by half the size of the hex-shape.

If you want more advanced features bundled all together and top performance check out my Canvas Multi-Grid constructor on Codecanyon

Canvas Multi-Grid constructor

Enjoy!

Facebooktwittergoogle_pluspinterestlinkedin
linkedin
Tagged , , , , , , . Bookmark the permalink.

3 Responses to Create grid patterns with canvas (blocks, diamonds, hex)

  1. nice article.. but you can expand this article with the another type of BLOCK pattern like thickness of each tenth line should be high then other lines horizontally and vertically.

  2. Please, how do I make lozenge shape?… I´ll use all these who u explain in this post, but, I´ll need t lozange too… can you help me?

  3. I’m sorry I am not familiar with this shape, the library is quite easy to change and modify to match your needs, but it requires some basic knowledge of geometry (for the shapes) and HTML5 Canvas.

Leave a Reply

Your email address will not be published. Required fields are marked *