Trying to make my first game this weekend. I finally got my rectangle to appear at the same time as my map. And my rectangle can move! But as soon as I click a button to move it, the map disappears. Is this where I need to make some kind of gameplay loop to keep updating the map on every button click or set a timer on it? Or do I have some other kind of error? Thanks all!
var canvas = <HTMLCanvasElement>document.getElementById('myCanvas');
var context = canvas.getContext("2d");
var img = new Image();
img.onload = function () {
context.drawImage(img, 0, 0);
}
img.src = "";
var mapArray =
["############################",
"# # # o ##",
"# #",
"# #### ##### ## #",
"## # # ## #",
"### ## # #",
"# ### # #",
"# #### ### #",
"# ## # o #",
"# o # # o ### ### #",
"# # # #",
"############################"];
//need to add wall.scource = and grass.source =
var wall = new Image();
var grass = new Image();
grass.src = "http://vignette2.wikia.nocookie.net/tibia/images/6/60/Grass_(Tile).gif/revision/latest?cb=20080817072800&path-prefix=en";
wall.src = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBwgHBgkIBwgKCgkLDRYPDQwMDRsUFRAWIB0iIiAdHx8kKDQsJCYxJyofLT0tMSw3QTo6LC87RD84Nzc5OjcBCgoKBQUFDgUFDisZExkrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrK//AABEIACAAIAMBIgACEQEDEQH/xAAYAAADAQEAAAAAAAAAAAAAAAACAwQFAP/EACkQAAEDAwIDCQEAAAAAAAAAAAECAxEABCESEyMxURQyM0Fhc4GT0QX/xAAUAQEAAAAAAAAAAAAAAAAAAAAA/8QAFBEBAAAAAAAAAAAAAAAAAAAAAP/aAAwDAQACEQMRAD8Au/oXDzT2ltZSJxAHKp27242yC5nPxQ3Qm5dVqzOMelI7vNMdYoKm718Jw4c85ApN5cXIbWvdUTtk48qBKkGcgEdaFRT2e4AIPCVQaF+1tvuawAVEQKlVBM8ulHfPoXeunfaKQqJ1ilrW0UnjNfYP2gVoCoURIpdwhoMuhKTG2ZNODiJI3miPcFddvMm1cSHGvDIEKBJoP//Z";
var posX = 0;
var posY = 0;
//for loops set images at given coordinates according to position on mapArray
for (var y = 0; y < mapArray.length; y++) {
for (var x = 0; x < mapArray[0].length; x++) {
if (mapArray[y][x] == "") {
context.drawImage(grass, (32 * x), (32 * y), 32, 32)//last two are size of image )
}
if (mapArray[y][x] == "#") {
context.drawImage(wall, (32 * x), (32 * y), 32, 32)//last two are size of image )
}
}
}
context.rect(posX, posY, 32, 32)
context.stroke();//traces path, might not need this
//moves character
function move(e) {//next five lines are newly added. Final line of function is drawimage function that is new as well
var ctx = canvas.getContext('2d');// create backing canvas
var backCanvas = document.createElement('canvas');
backCanvas.width = canvas.width;
backCanvas.height = canvas.height;
var backCtx = backCanvas.getContext('2d');
//alert(e.keyCode);//gives feedback to what each keyCode is
if (e.keyCode == 39) {
posX += 5;
}
if (e.keyCode == 37) {
posX -= 5;
}
if (e.keyCode == 40) {
posY += 5;
}
if (e.keyCode == 38) {
posY -= 5;
}
canvas.width = canvas.width;//clears the board after each move
context.rect(posX, posY, 32, 32)
context.stroke();
ctx.drawImage(backCanvas, 0, 0);
}
document.onkeydown = move;