Skip to content Skip to sidebar Skip to footer

How Do I Draw Circles On A Checker-board's Squares To Make It Look Like A Real Checker-board?

I have managed to draw a checker-board with JavaScript and canvas. The problem I have now is making sure my code gives output like the real checker picture here: What can I do wit

Solution 1:

Like your previous question, a good answer depends on a good representation. If you're building a real game, the game code will want to state which square to draw which piece, something like this.

const canvas = document.querySelector('canvas')
const c = canvas.getContext('2d')
//make a teal colored rectangle
c.fillStyle = '#ccc'
c.fillRect(0, 0, 100, 100)
//make a pink rectangle
c.fillStyle = '#fff'
c.fillRect(100, 100, 100, 100)
//create rectangle objectfunctionRectangle(x, y, width, height, color) {
  this.x = x
  this.y = y
  this.width = width
  this.height = height
  this.color = color
  this.draw = function() {
    c.fillStyle = this.color
    c.fillRect(this.x, this.y, this.width, this.height)
  }
}

 const squarePx = 100// const cols = 4, rows = Math.ceil(canvas.height / squarePx)const cols = 8, rows = 8for (let col = 0; col < cols; col++) {
   for (let row = 0; row < rows; row++) {
     let x = col * squarePx, y = row * squarePx
     // on even rows, even cols are dark. on odd rows, odd cols are darklet evenRow = row % 2 === 0, evenCol = col % 2 === 0let fillStyle = evenRow === evenCol ? '#222' : '#888'// draw at x, y, using fillStylelet rectangle = newRectangle(x, y, squarePx, squarePx, fillStyle)
     rectangle.draw()
   }
 }
 
 functiondrawChecker(row, col, color) {
   c.fillStyle = color;
   c.beginPath();
   c.arc((col*squarePx)+50, (row*squarePx)+50, 25, 25, 0, 2*Math.PI);
   c.fill();
}
 
 // draw some checkers in initial positionsfor (let row = 0; row<2; row++) {
  for (let col = 0; col<8; col++) {
    let evenRow = row % 2 === 0, evenCol = col % 2 === 0if (evenRow !== evenCol) drawChecker(row, col, 'red')
  }
}

 for (let row = 6; row<8; row++) {
  for (let col = 0; col<8; col++) {
    let evenRow = row % 2 === 0, evenCol = col % 2 === 0if (evenRow === evenCol) drawChecker(row, col, 'white')
  }
}
<html><head></head><body><canvaswidth='800'height='800'></canvas></body>

Post a Comment for "How Do I Draw Circles On A Checker-board's Squares To Make It Look Like A Real Checker-board?"