Painting the tile map to the Canvas
Demo
<!DOCTYPE html>
<html>
<head>
<style>
#canvas { /* w w w . j av a 2 s .com*/
border:1px solid #03F;
background:#CFC;
}
</style>
</head>
<body>
<p>Here is the sprite image:</p>
<img src='http://java2s.com/style/demo/tank1.png'/>
<canvas id="canvas" width="640" height="480"></canvas>
<script>
let context = document.getElementById('canvas').getContext('2d');
let tileSheet = new Image();
tileSheet.addEventListener('load', eventSheetLoaded , false);
tileSheet.src = "http://java2s.com/style/demo/tank1.png";
let mapIndexOffset = -1;
let mapRows = 10;
let mapCols = 10;
let tileMap = [
[32,31,31,31,1,31,1,1,1,32]
, [1,1,1,1,1,1,1,1,1,1]
, [32,1,26,1,26,1,26,1,1,32]
, [32,26,1,1,26,1,1,26,1,32]
, [32,1,1,1,26,26,1,26,1,32]
, [32,1,1,26,1,1,1,26,1,32]
, [32,1,1,1,1,1,1,26,1,32]
, [1,1,26,1,26,1,26,1,1,1]
, [32,1,1,1,1,1,1,1,1,32]
, [32,31,31,31,1,31,31,1,31,32]
];
function eventSheetLoaded() {
drawScreen()
}
function drawScreen() {
for (let rowCtr=0;rowCtr<mapRows;rowCtr++) {
for (let colCtr=0;colCtr<mapCols;colCtr++){
let tileId = tileMap[rowCtr][colCtr]+mapIndexOffset;
let sourceX = Math.floor(tileId % 8) *32;
let sourceY = Math.floor(tileId / 8) *32;
context.drawImage(tileSheet, sourceX,
sourceY,32,32,colCtr*32,rowCtr*32,32,32);
}
}
}
</script>
</body>
</html>