HTML5 Game - Drawing the Canvas Grid

Introduction

The following code shows how to do drawing using the canvas element for the grid system.

Demo

ResultView the demo in separate window

<!DOCTYPE html>  
<html> 
<head> 
<style> 
#canvas { /*from   www  .  j  a v a 2  s . c  o  m*/
  border:1px solid #03F; 
  background:#CFC; 
} 
</style> 
<script> 

let canvas; 
let context; 

function showGrid() { 
  canvas = document.getElementById('canvas'); 
  context = canvas.getContext( '2d'); 

  context.lineWidth = 1; 
  context.strokeStyle = '#999'; 

  lineSpacing = 100; 

  let xPos = 0; 
  let yPos = 0; 

  let numHorizontalLines = parseInt(canvas.height/lineSpacing); 
  let numVerticalLines = parseInt(canvas.width/lineSpacing); 

  for (let i=1; i<=numHorizontalLines;i++) { 
            yPos = i*lineSpacing; 
            context.moveTo(0,yPos); 
            context.lineTo(canvas.width,yPos); 
            context.stroke(); 
          } 
          for (let i=1; i<=numVerticalLines;i++) { 
            xPos = i*lineSpacing; 
            context.moveTo(xPos,0); 
            context.lineTo(xPos,canvas.height); 
            context.stroke(); 
          } 

          for (let y=0; y<=numHorizontalLines; y++) { 
            for (let x=0; x<=numVerticalLines; x++) { 
              xPos = x*lineSpacing; 
              yPos = y*lineSpacing; 

              if (x==0 && y==0) { 
                context.fillStyle='#f00'; 
              } else { 
                context.fillStyle='#000'; 
              } 

              context.beginPath(); 
              context.arc(xPos,yPos,5,0,Math.PI*2,true); 
              context.closePath(); 
              context.fill(); 

              if (x==numVerticalLines) { 
                context.textAlign = 'right'; 
                xPos -= 5; 
              } else { 
                context.textAlign = 'left'; 
                xPos += 5; 
              } 
              if (y==numHorizontalLines) { 
                yPos -= 8; 

      } else { 
        yPos += 12; 
      } 
      context.fillText('('+x*lineSpacing+','+y*lineSpacing+')',xPos,yPos); 
    } 
  } 
} 

window.addEventListener('load',showGrid,false); 
</script> 
</head> 
<body> 
  <h1>Canvas Grid System</h1> 
  <canvas id="canvas" width="600" height="400"> 
    The Canvas HTML5 element is not supported by your browser. 
    Please run this page in a different browser. 
  </canvas> 
</body> 
</html>

Related Topic