<html>
<head>
<title>TileMap2</title>
<style>
#canvas {
outline: 3px solid black;
}
</style>
</head>
<body>
<canvas id="canvas" height="400" width="1000"></canvas>
<script>
window.onload = function() {
drawMap();
}
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
canvas.width = "1000";
canvas.height = "400";
var xpos = 0;
var ypos = 0;
var grass = new Image();
var water = new Image();
var dirt = new Image();
var mario = new Image();
mario.src = 'Mario.png';
grass.src = 'grass1.jpg';
water.src = 'water.jpg';
dirt.src = 'dirt.jpg';
var map = [
[1, 1, 0, 1, 1, 1, 1, 0, 1, 1],
[1, 1, 0, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 0, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 0, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 0, 1, 1, 1, 1, 1, 1, 1]
];
function drawMap() {
for (var i = 0; i < map.length; i++) {
for (var j = 0; j < map[i].length; j++) {
if (parseInt(map[i][j]) == 0) {
context.drawImage(grass, xpos, ypos);
}
if (parseInt(map[i][j]) == 1) {
context.drawImage(dirt, xpos, ypos)
};
if (parseInt(map[i][j]) == 2) {
context.drawImage(water, xpos, ypos);
}
xpos += 100;
}
xpos = 0;
ypos += 100;
}
xpos = 0;
ypos = 0;
context.drawImage(mario, xpos, ypos, 50, 50);
}
function move(e) {
if (e.keyCode == 39) {
xpos += 50;
}
if (e.keyCode == 37) {
xpos -= 50;
}
if (e.keyCode == 38) {
ypos -= 50;
}
if (e.keyCode == 40) {
ypos += 50;
}
canvas.width = canvas.width;
context.drawImage(mario, xpos, ypos, 50, 50);
}
document.onkeydown = move;
</script>
</body>
</html>
The problem is that when i am pressing the arrow keys mario moves but the grass,dirt,water images disapper and the only thing remaining is mario moving in a canvas. That problem is solved if i type in the move function canvas.width=canvas.width but then mario moves leaving highlights of his previous positions on the canvas.