How to add images on a gameMap in JavaScript?

I have a game map where 1's are path and 0's are wall. I'm trying to add an image where wall is but somehow the images are not at the right places. I know I have my Maths wrong somewhere but not sure where, can someone help please.

JavaScript

var ctx = null;
// 1's are path 
var gameMap = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                1, 1, 1, 0, 1, 1, 1, 0, 0, 0,
                0, 0, 1, 0, 1, 0, 1, 0, 0, 0,
                0, 0, 1, 1, 1, 0, 1, 0, 0, 0,
                0, 0, 0, 0, 0, 0, 1, 1, 1, 0,
                0, 0, 1, 1, 1, 0, 0, 0, 1, 0,
                0, 0, 1, 0, 1, 1, 1, 1, 1, 0,
                0, 0, 1, 0, 0, 0, 0, 0, 0, 0,
                0, 0, 1, 1, 1, 1, 1, 1, 1, 1,
                0, 0, 0, 0, 0, 0, 0, 0, 0, 0
];
var tileW = 40, tileH = 40; 
var mapW = 10, mapH = 10; 

...

window.onload = function() {
    ctx = document.getElementById('game').getContext("2d");
    requestAnimationFrame(drawGame);
    ctx.font = "bold 10pt sans-serif";  
};

....

function drawGame() {
    if (ctx == null) {
        return;
    }

...

    var image = new Image();
    image.src = "images/brick.png";
    
    // Creating tiles
    for (var y = 0; y < mapH; ++y) {
        for (var x = 0; x < mapW; ++x) {
            switch (gameMap[((y * mapW) + x)]) {
                case 0:
                    ctx.fillStyle = "lightgray";  // These tiles are on correct places.
                    
                    ctx.drawImage(image, y * tileH, x * tileW, tileH, tileW); // These images are not on the correct places.
                    break;
                default:
                    ctx.fillStyle = "white";
                    break;
            }
            ctx.strokeStyle = "lightgray"; 
            ctx.strokeRect(x * tileW, y * tileH, tileW, tileH);
            ctx.fillRect(x * tileW, y * tileH, tileW, tileH);
        }
    }

    ctx.fillStyle = "red"; 
    ctx.fillStyle = "#ff0000";
    requestAnimationFrame(drawGame);
}

Solution 1:

It appears to me that you draw the brick image first, and then using fillRect to cover it. That might be the reason for your problem.

Also, you might have x and y in the different position in the drawImage?

ctx.drawImage(image, y * tileH, x * tileW, tileH, tileW); // These images are not on the correct places.