var canvas = document.getElementById("canvas1");
var ctx = canvas.getContext("2d");
var grass = new Image();
var sand = new Image();
grass.src = "http"https://i42i.tinypicsstatic.comnet/2ljm6w9PTwXZ.png";
sand.src = "http"https://www.tibiawikii.comsstatic.br/images/7/7anet/Sand_TileTtWhX.gif";
var images = [grass, sand];
var tsize = 32; // Tile size.
var mapArray = [[0,0,0,0,0,0,0,0,0,1,0,0,0],
[0,0,0,0,0,0,0,0,0,1,0,0,0],
[0,0,0,0,0,0,0,0,0,1,0,0,0],
[0,0,0,0,0,0,0,0,0,1,0,0,0],
[0,0,0,0,0,0,0,0,0,1,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0],
[1,1,1,1,1,1,1,1,1,1,1,1,1]];
var fieldWidth = mapArray[0].length;
var fieldHeight = mapArray.length;
// Cam configs.
var camX = 0;
var camY = 0;
var camWidth = 320;
var camHeight = 160;
// Others.
var offsetX = 0;
var offsetY = 0;
function draw() {
requestAnimationFrame(draw);
var startCol = Math.floor(camX / tsize);
var endCol = startCol + (camWidth /tsize);
var startRow = Math.floor(camY / tsize);
var endRow = startRow + (camHeight / tsize);
var offsetX = -camX + startCol * tsize;
var offsetY = -camY + startRow * tsize;
console.log(startCol + "," + endCol + "," + startRow + "," + endRow);
ctx.fillStyle = "#0000FF";
ctx.fillRect(0, 0, camWidth, camHeight);
for (var r = Math.max(0, startRow); r <= endRow && r < fieldHeight; r++) {
for (var c = Math.max(0, startCol); c <= endCol && c < fieldWidth; c++) {
var x = (c - startCol) * tsize + offsetX;
var y = (r - startRow) * tsize + offsetY;
ctx.drawImage(images[mapArray[r][c]], x, y);
}
}
}
document.addEventListener("keydown", function(e) {
if (e.keyCode == 40) {
camY += 1;
e.preventDefault();
}
if (e.keyCode == 39) {
camX += 1;
e.preventDefault();
}
if (e.keyCode == 38) {
camY -= 1;
e.preventDefault();
}
if (e.keyCode == 37) {
camX -= 1;
e.preventDefault();
}
});
draw();
<html>
<head>
<title>Scrolling Tiled Map</title>
</head>
<body>
<canvas id="canvas1" width="320" height="160" style = "border: 1px solid black;"></canvas>
<script src="javascript.js"></script>
</body>
</html>