Here is my script, I can't seem to figure out what's wrong, I want to draw a tile map 12*12 and the tiles are 32px - 32px. The tiles dont draw when I run the page, Ive tried using parse int as shown below but still, it didn't work.
if(parseInt(mapArray[x][y]) == 0){
ctx.drawImage(rockTile, posX, posY, tileSize, tileSize);
}
Here is the script I have created.
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = (32 * 12);
canvas.height = (32 * 12);
document.body.appendChild(canvas);
var rockTile = new Image();
rockTile.src = "../Images/dc-dngn/floor/rect_gray0.png";
var tileSize = 32;
var posX = 0;
var posY = 0;
var mapArray = [
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
];
$(document).ready(function(){
drawMap();
});
function drawMap(){
for(var x = 0; x < mapArray.length; x++){
for(var y = 0; y < mapArray[x].length; y++){
if(mapArray[x][y] == 0){
ctx.drawImage(rockTile, posX, posY, tileSize, tileSize);
}
posX += 32;
}
posX = 0;
posY += 32;
}
}
If anyone can help me to get my tiles to draw that would greatly appreciated, Thank you!
You must wait for the image to load. That image is not part of the DOM and therefore waiting for the loading of the document won't help.
You need to place an handler for the image.onload slot and trigger a redraw when that code is called.
The normal procedure is
src valueonly when the registered event is called you can use the image object.
The tricky part is that, depending on the browser, the image may become instantly valid after setting src if it's already in the cache, so when you don't follow the correct procedure things may apparently work anyway (but they will not work in real cases when loading requires internet access).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With