0

Is there a way to get an image in Javascript? By this, I mean, get an image by URL, and then be able to draw it in an HTML canvas using the ctx.drawIamge() function?

I'm using this to make a chess game, and wanted to use custom images for this. Here's my code so far:

let ctx = document.getElementById("gm").getContext("2d");
let board = [
  ["bR", "bN", "bB", "bQ", "bK", "bB", "bN", "wR"],
  ['bP','bP','bP','bP','bP','bP','bP','bP'],
  ['','','','','','','',''],
  ['','','','','','','',''],
  ['','','','','','','',''],
  ['','','','','','','',''],
  ['wP','wP','wP','wP','wP','wP','wP','wP'],
  ["wR", "wN", "wB", "wQ", "wK", "wB", "wN", "wR"]
  ]
function fillSquare(color, x, y) {
  ctx.fillStyle = color;
  ctx.fillRect(x, y, 64, 64);
}

function drawGrid() {
  color = "#3c9653";
  x = 0;
  y = 0;
  for (let x1 = 0; x1 <= 7; x1++) {
    for (let y1 = 0; y1 <= 7; y1++) {
    
      fillSquare(color, x * 64, y * 64);
      if (color == "#3c9653") {
        color = "#d2dba2";
      }
      else {
        color = "#3c9653";
      }
      x++;
    }
    if (color == "#3c9653") {
      color = "#d2dba2";
    }
    else {
      color = "#3c9653";
    }
    y = y + 1;
    x = 0;

  }
  

}
function drawPieces(grid) {
  let px = 5;
  let py = 5;
  for (row of grid) {
    for (piece of row) {
      if (piece == "wR") {
        piece_img = require("./imgs/white/wrook.png");
        console.log(piece_img);
        ctx.drawImage(piece_img, px, py);
      }
      px = px + 64;

    }
    py = py + 64;
  }
}
drawGrid();
drawPieces(board);

The way I tried to do this, is using a require() function, but that cannot be used in normal JS, (or according to the error I got):

ReferenceError: require is not defined
    at drawPieces (/script.js:52:9)
    at /script.js:63:1
  • I know you want drawImage, but you could also do table filled with 1px by 1px sized table cells, and then change their color based on the image matrix. You might need to convert your image into websafe colors however. – Paul Nikonowicz Sep 20 '20 at 22:04
  • FYI, your `drawGrid` can be much shorter. `function drawGrid() { const colors = ["#3c9653", "#d2dba2"]; for (let i = 0; i < 64; i++) { fillSquare(colors[i % 2], Math.floor(i / 8) * 64, (i % 8) * 64) } }` –  Sep 20 '20 at 22:17

0 Answers0