Canvas draw grid as backgound

Asked

Viewed 60 times

0

I did some research but I didn’t find much information. What I intend to do is draw a grid as a background in the canvas. I saw some examples with svg and others directly on the canvas. Assuming that I will allow you to zoom in and drag the scene of the canvas among other information. Which is the best option?

  • With CSS it would not be an option for you??

2 answers

1

I believe this will help.

  const canvas = document.querySelector("canvas")
  const c = canvas.getContext("2d")

 canvas.width = 400;
 canvas.height = 400;

 const tileCount = 20;
 let gridX = canvas.width / tileCount;
 let gridY = canvas.height / tileCount;


function drawGrid() {
  c.strokeStyle = "rgba(255, 0, 0)"
   for (let i = 0; i < gridX; i++) {
     for (let j = 0; j < gridY; j++) {
        c.rect(i*tileCount, j*tileCount, tileCount, tileCount)

    }
}
c.stroke()
}

drawGrid()

0

Well, I know I already answered this post, however, I wanted to share how to develop a colorful grid that I developed for my Snake Game, just change the colors to suit your taste.

 const tileCount = 20;
 const gridX = canvas.width / tileCount;
 const gridY = canvas.height / tileCount;


 function drawGrid() {
     for (let i = 0; i < gridX; i++) {
         for (let j = 0; j <gridY; j++) {
              if((j+i) % 2 == 0){
                   c.fillStyle = "#B2DD72" 
                   c.fillRect(i*tileCount, j*tileCount, tileCount, tileCount)
               }else{
                   c.fillStyle = "#74BF75"
                   c.fillRect(i*tileCount, j*tileCount, tileCount, tileCount)
               }      
            }
        }
    }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.