HTML5 Game - Canvas Shape Grid

Description

Grid

Demo

ResultView the demo in separate window

<!doctype html>
<html>
<body>
<canvas id="canvas" width="700" height="500" style='border:1px black'></canvas>
<script>
'use strict'//from w  w  w  .  j a  v a2  s  .c o  m
let canvas = document.getElementById('canvas');
let context = canvas.getContext('2d'); 


function drawGrid(context, config){
    context.save();

    let gridEndingX=config.startX+ config.cellWidth*config.columnCount;
    let gridEndingY=config.startY+ config.cellHeight*config.rowCount;
        
    context.beginPath() ;    
    for (let i=0; i<=config.columnCount; i++){
      context.moveTo(config.startX+config.cellWidth*i,config.startY);
      context.lineTo(config.startX+config.cellWidth*i,gridEndingY);
    }
    for (let j=0; j<=config.rowCount; j++){
      context.moveTo(config.startX,config.startY+config.cellHeight*j);
      context.lineTo(gridEndingX,config.startY+config.cellHeight*j);
    }
    context.stroke(); 
   
    context.restore();
}

drawGrid(context, {startX:600,
                   startY:50,
                   cellWidth: 30,
                   cellHeight: 30,
                   rowCount : 3,
                   columnCount:3
                   });
                   
drawGrid(context, {startX:600,
                   startY:200,
                   cellWidth: 30,
                   cellHeight: 30,
                   rowCount : 3,
                   columnCount:3
                   });

drawGrid(context, {startX:600,
                   startY:350,
                   cellWidth: 30,
                   cellHeight: 30,
                   rowCount : 3,
                   columnCount:3
                   });
                   
drawGrid(context, {startX:50,
                   startY:50,
                   cellWidth: 30,
                   cellHeight: 30,
                   rowCount : 10,
                   columnCount:10
                   });
  </script>
</body>
</html>

Related Topics