Animated Sprites in Canvas
canvasgamedevtilemaptutorialgraphicsjavascripthtmlarchivedAnimating Canvas Sprites
It's not difficult to convert the sprites we're using to animated sprites. All we have to do is make sure our tileset has several frames for the sprites we want to animate, and make some small changes to our code. To begin with, we'll add support for animated map tiles, and test this by (badly) animating the water sprite.

We're going to modify the tileTypes array, but just the water entry. Our new water code will look like this:
4 : { colour:"#678fd9", floor:floorTypes.water, sprite:[
{x:160,y:0,w:40,h:40,d:200}, {x:200,y:0,w:40,h:40,d:200},
{x:160,y:40,w:40,h:40,d:200}, {x:200,y:40,w:40,h:40,d:200},
{x:160,y:40,w:40,h:40,d:200}, {x:200,y:0,w:40,h:40,d:200}
]}
In our sprite property we've added 5 more sets of information, whos x,y properties correspond to our new water frames positions on our tilesheets, and w,h properties correspond to the tileW, tileH values we have set.
Each entry also has a new d property, which we use to set the duration that frame will be displayed for in milliseconds before the next frame is drawn.
Processing sprite data
An additional bit of processing in the windows onload function will be added to make the tileTypes sprite property even more useful for our code. First, loop over the tileTypes array:
for(x in tileTypes)
{
We'll check the sprite property of each, and if we've provided more than one frame worth of data we'll flag the sprite as animated; otherwise we'll flag it as not animated:
tileTypes[x]['animated'] = tileTypes[x].sprite.length > 1 ? true : false;
Now, if this sprite is animated, we have more work to do. Firstly, we need to create a temporary variable t, which will be a time counter for the duration of each frame:
if(tileTypes[x].animated)
{
var t = 0;
We'll also loop over every frame we have data for in the sprite array.
for(s in tileTypes[x].sprite)
{
For each frame, we'll set the start time of the sprite to the current accumulated value of the t variable:
tileTypes[x].sprite[s]['start'] = t;
We can now add the duration of this frame (d) to the value of t, and set this accumulated value as the end property of this frame:
t+= tileTypes[x].sprite[s].d;
tileTypes[x].sprite[s]['end'] = t;
We're done with editing information for the frames of this tileTypes sprite, so we'll close the frame loop, after which we'll set a spriteDuration property for the tileType we're currently processing as the accumulated final value of the t variable, and then close the processing loops.
}
tileTypes[x]['spriteDuration'] = t;
}
}
A helper function for frame finding
Now that we have all this information for the frames of our sprite, we can create a helper function to find the current frame data of a sprite. our new getFrame function will take 4 arguments; the sprite, which is an array of frames, the duration, which is the spriteDuration property, ie: the complete duration of the sprite if all frames are counted, the time, which is the current game time in milliseconds, and animated, a boolean flag which states whether or not the sprite is animated.
function getFrame(sprite, duration, time, animated)
{
First, we'll check the animated flag to see if we have multiple frames. If not, we just return the first frame (index 0):
if(!animated) { return sprite[0]; }
Next, we perform a modulus operation on the time argument; the value of time is divided by the total sprite duration, and the time variable is updated to the remainder of this sum. This allows sprites to "loop".
time = time % duration;
Finally, we loop over the frames of the sprite. If the end time of the sprite occurs at or after the time value we're looking for for the current frame, we return this frame. This will find us the correct frame, so we can then close this function.
for(x in sprite)
{
if(sprite[x].end>=time) { return sprite[x]; }
}
}
Updating rendering
Finally, as we're only adding full support for animated tile sprites in this example, we only need to modify the sprite drawing code inside the y,x nested loops in the drawGame function for tile rendering.
After we have assigned the current x,y tileType to our temporary tile variable inside these loops, we can then create a temporary sprite variable, and use our getFrame helper function to find the current frame:
var sprite = getFrame(tile.sprite, tile.spriteDuration,
currentFrameTime, tile.animated);
We're passing the method the sprite, duration, and animated arguments from the tile properties, and the time argument from the current game time (currentFrameTime).
The method returns us the appropriate set of x,y, w,h values from the sprite array, which we can then use the render to the canvas with minor changes to the drawImage code:
ctx.drawImage(tileset,
sprite.x, sprite.y, sprite.w, sprite.h,
viewport.offset[0] + (x*tileW), viewport.offset[1] + (y*tileH),
tileW, tileH);
If you now load up your HTML document you should have a (terrible) animation effect on the maps water sprites!
Modified source code
<!DOCTYPE html> <html> <head> <script type="text/javascript"> var ctx = null; var gameMap = [ 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 2, 2, 0, 0, 2, 3, 4, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 2, 2, 0, 0, 2, 3, 1, 4, 4, 1, 1, 2, 2, 2, 2, 1, 1, 2, 2, 2, 2, 2, 0, 0, 2, 3, 1, 1, 4, 4, 1, 2, 3, 3, 2, 1, 1, 2, 1, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 2, 4, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 2, 4, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 2, 4, 4, 4, 4, 4, 1, 1, 1, 2, 2, 2, 2, 1, 0, 0, 1, 1, 1, 1, 2, 3, 2, 1, 1, 4, 1, 1, 1, 1, 3, 3, 2, 1, 0, 0, 1, 2, 2, 2, 2, 1, 2, 1, 1, 4, 1, 1, 1, 1, 1, 3, 2, 1, 0, 0, 1, 2, 3, 3, 2, 1, 2, 1, 1, 4, 4, 4, 4, 4, 4, 4, 2, 4, 4, 0, 1, 2, 3, 3, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 0, 0, 1, 2, 3, 4, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 0, 1, 2, 1, 0, 0, 3, 2, 3, 4, 4, 1, 2, 2, 2, 2, 2, 2, 2, 1, 0, 1, 2, 1, 0, 0, 3, 2, 3, 4, 4, 3, 2, 1, 1, 1, 1, 1, 2, 1, 1, 1, 2, 3, 0, 0, 3, 2, 3, 4, 1, 3, 2, 1, 3, 1, 1, 1, 2, 1, 1, 1, 2, 3, 0, 0, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 1, 1, 2, 2, 2, 2, 2, 3, 0, 0, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]; var tileW = 40, tileH = 40; var mapW = 20, mapH = 20; var currentSecond = 0, frameCount = 0, framesLastSecond = 0, lastFrameTime = 0; var tileset = null, tilesetURL = "tileset.jpg", tilesetLoaded = false;; var floorTypes = { solid : 0, path : 1, water : 2 }; var tileTypes = { 0 : { colour:"#685b48", floor:floorTypes.solid, sprite:[{x:0,y:0,w:40,h:40}] }, 1 : { colour:"#5aa457", floor:floorTypes.path, sprite:[{x:40,y:0,w:40,h:40}] }, 2 : { colour:"#e8bd7a", floor:floorTypes.path, sprite:[{x:80,y:0,w:40,h:40}] }, 3 : { colour:"#286625", floor:floorTypes.solid, sprite:[{x:120,y:0,w:40,h:40}] },4 : { colour:"#678fd9", floor:floorTypes.water, sprite:[ {x:160,y:0,w:40,h:40,d:200}, {x:200,y:0,w:40,h:40,d:200}, {x:160,y:40,w:40,h:40,d:200}, {x:200,y:40,w:40,h:40,d:200}, {x:160,y:40,w:40,h:40,d:200}, {x:200,y:0,w:40,h:40,d:200} ]}
}; var directions = { up : 0, right : 1, down : 2, left : 3 }; var keysDown = { 37 : false, 38 : false, 39 : false, 40 : false }; var viewport = { screen : [0,0], startTile : [0,0], endTile : [0, 0], offset : [0,0], update : function(px, py) { this.offset[0] = Math.floor((this.screen[0]/2) - px); this.offset[1] = Math.floor((this.screen[1]/2) - py); var tile = [ Math.floor(px/tileW), Math.floor(py/tileH) ]; this.startTile[0] = tile[0] - 1 - Math.ceil((this.screen[0]/2) / tileW); this.startTile[1] = tile[1] - 1 - Math.ceil((this.screen[1]/2) / tileH); if(this.startTile[0] < 0) { this.startTile[0] = 0; } if(this.startTile[1] < 0) { this.startTile[1] = 0; } this.endTile[0] = tile[0] + 1 + Math.ceil((this.screen[0]/2) / tileW); this.endTile[1] = tile[1] + 1 + Math.ceil((this.screen[1]/2) / tileH); if(this.endTile[0] >= mapW) { this.endTile[0] = mapW-1; } if(this.endTile[1] >= mapH) { this.endTile[1] = mapH-1; } } }; var player = new Character(); function Character() { this.tileFrom = [1,1]; this.tileTo = [1,1]; this.timeMoved = 0; this.dimensions = [30,30]; this.position = [45,45]; this.delayMove = 700; this.direction = directions.up; this.sprites = {}; this.sprites[directions.up] = [{x:0,y:120,w:30,h:30}]; this.sprites[directions.right] = [{x:0,y:150,w:30,h:30}]; this.sprites[directions.down] = [{x:0,y:180,w:30,h:30}]; this.sprites[directions.left] = [{x:0,y:210,w:30,h:30}]; } Character.prototype.placeAt = function(x, y) { this.tileFrom = [x,y]; this.tileTo = [x,y]; this.position = [((tileW*x)+((tileW-this.dimensions[0])/2)), ((tileH*y)+((tileH-this.dimensions[1])/2))]; }; Character.prototype.processMovement = function(t) { if(this.tileFrom[0]==this.tileTo[0] && this.tileFrom[1]==this.tileTo[1]) { return false; } if((t-this.timeMoved)>=this.delayMove) { this.placeAt(this.tileTo[0], this.tileTo[1]); } else { this.position[0] = (this.tileFrom[0] * tileW) + ((tileW-this.dimensions[0])/2); this.position[1] = (this.tileFrom[1] * tileH) + ((tileH-this.dimensions[1])/2); if(this.tileTo[0] != this.tileFrom[0]) { var diff = (tileW / this.delayMove) * (t-this.timeMoved); this.position[0]+= (this.tileTo[0]<this.tileFrom[0] ? 0 - diff : diff); } if(this.tileTo[1] != this.tileFrom[1]) { var diff = (tileH / this.delayMove) * (t-this.timeMoved); this.position[1]+= (this.tileTo[1]<this.tileFrom[1] ? 0 - diff : diff); } this.position[0] = Math.round(this.position[0]); this.position[1] = Math.round(this.position[1]); } return true; } Character.prototype.canMoveTo = function(x, y) { if(x < 0 || x >= mapW || y < 0 || y >= mapH) { return false; } if(tileTypes[gameMap[toIndex(x,y)]].floor!=floorTypes.path) { return false; } return true; }; Character.prototype.canMoveUp = function() { return this.canMoveTo(this.tileFrom[0], this.tileFrom[1]-1); }; Character.prototype.canMoveDown = function() { return this.canMoveTo(this.tileFrom[0], this.tileFrom[1]+1); }; Character.prototype.canMoveLeft = function() { return this.canMoveTo(this.tileFrom[0]-1, this.tileFrom[1]); }; Character.prototype.canMoveRight = function() { return this.canMoveTo(this.tileFrom[0]+1, this.tileFrom[1]); }; Character.prototype.moveLeft = function(t) { this.tileTo[0]-=1; this.timeMoved = t; this.direction = directions.left; }; Character.prototype.moveRight = function(t) { this.tileTo[0]+=1; this.timeMoved = t; this.direction = directions.right; }; Character.prototype.moveUp = function(t) { this.tileTo[1]-=1; this.timeMoved = t; this.direction = directions.up; }; Character.prototype.moveDown = function(t) { this.tileTo[1]+=1; this.timeMoved = t; this.direction = directions.down; }; function toIndex(x, y) { return((y * mapW) + x); }function getFrame(sprite, duration, time, animated) { if(!animated) { return sprite[0]; } time = time % duration; for(x in sprite) { if(sprite[x].end>=time) { return sprite[x]; } } }
window.onload = function() { ctx = document.getElementById('game').getContext("2d"); requestAnimationFrame(drawGame); ctx.font = "bold 10pt sans-serif"; window.addEventListener("keydown", function(e) { if(e.keyCode>=37 && e.keyCode<=40) { keysDown[e.keyCode] = true; } }); window.addEventListener("keyup", function(e) { if(e.keyCode>=37 && e.keyCode<=40) { keysDown[e.keyCode] = false; } }); viewport.screen = [document.getElementById('game').width, document.getElementById('game').height]; tileset = new Image(); tileset.onerror = function() { ctx = null; alert("Failed loading tileset."); }; tileset.onload = function() { tilesetLoaded = true; }; tileset.src = tilesetURL;for(x in tileTypes) { tileTypes[x]['animated'] = tileTypes[x].sprite.length > 1 ? true : false; if(tileTypes[x].animated) { var t = 0; for(s in tileTypes[x].sprite) { tileTypes[x].sprite[s]['start'] = t; t+= tileTypes[x].sprite[s].d; tileTypes[x].sprite[s]['end'] = t; } tileTypes[x]['spriteDuration'] = t; } }
}; function drawGame() { if(ctx==null) { return; } if(!tilesetLoaded) { requestAnimationFrame(drawGame); return; } var currentFrameTime = Date.now(); var timeElapsed = currentFrameTime - lastFrameTime; var sec = Math.floor(Date.now()/1000); if(sec!=currentSecond) { currentSecond = sec; framesLastSecond = frameCount; frameCount = 1; } else { frameCount++; } if(!player.processMovement(currentFrameTime)) { if(keysDown[38] && player.canMoveUp()) { player.moveUp(currentFrameTime); } else if(keysDown[40] && player.canMoveDown()) { player.moveDown(currentFrameTime); } else if(keysDown[37] && player.canMoveLeft()) { player.moveLeft(currentFrameTime); } else if(keysDown[39] && player.canMoveRight()) { player.moveRight(currentFrameTime); } } viewport.update(player.position[0] + (player.dimensions[0]/2), player.position[1] + (player.dimensions[1]/2)); ctx.fillStyle = "#000000"; ctx.fillRect(0, 0, viewport.screen[0], viewport.screen[1]); for(var y = viewport.startTile[1]; y <= viewport.endTile[1]; ++y) { for(var x = viewport.startTile[0]; x <= viewport.endTile[0]; ++x) { var tile = tileTypes[gameMap[toIndex(x,y)]];var sprite = getFrame(tile.sprite, tile.spriteDuration, currentFrameTime, tile.animated); ctx.drawImage(tileset, sprite.x, sprite.y, sprite.w, sprite.h, viewport.offset[0] + (x*tileW), viewport.offset[1] + (y*tileH), tileW, tileH);
} } var sprite = player.sprites[player.direction]; ctx.drawImage(tileset, sprite[0].x, sprite[0].y, sprite[0].w, sprite[0].h, viewport.offset[0] + player.position[0], viewport.offset[1] + player.position[1], player.dimensions[0], player.dimensions[1]); ctx.fillStyle = "#ff0000"; ctx.fillText("FPS: " + framesLastSecond, 10, 20); lastFrameTime = currentFrameTime; requestAnimationFrame(drawGame); } </script> </head> <body> <canvas id="game" width="400" height="400"></canvas> </body> </html>
Animated Sprites source code
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var ctx = null;
var gameMap = [
0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 2, 4, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 2, 2, 0,
0, 2, 3, 4, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 2, 2, 0,
0, 2, 3, 1, 4, 4, 1, 1, 2, 2, 2, 2, 1, 1, 2, 2, 2, 2, 2, 0,
0, 2, 3, 1, 1, 4, 4, 1, 2, 3, 3, 2, 1, 1, 2, 1, 0, 0, 0, 0,
0, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 2, 2, 2, 2, 1, 1, 1, 1, 0,
0, 1, 1, 1, 1, 2, 4, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 0,
0, 1, 1, 1, 1, 2, 4, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 0,
0, 1, 1, 1, 1, 2, 4, 4, 4, 4, 4, 1, 1, 1, 2, 2, 2, 2, 1, 0,
0, 1, 1, 1, 1, 2, 3, 2, 1, 1, 4, 1, 1, 1, 1, 3, 3, 2, 1, 0,
0, 1, 2, 2, 2, 2, 1, 2, 1, 1, 4, 1, 1, 1, 1, 1, 3, 2, 1, 0,
0, 1, 2, 3, 3, 2, 1, 2, 1, 1, 4, 4, 4, 4, 4, 4, 4, 2, 4, 4,
0, 1, 2, 3, 3, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 0,
0, 1, 2, 3, 4, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 0, 1, 2, 1, 0,
0, 3, 2, 3, 4, 4, 1, 2, 2, 2, 2, 2, 2, 2, 1, 0, 1, 2, 1, 0,
0, 3, 2, 3, 4, 4, 3, 2, 1, 1, 1, 1, 1, 2, 1, 1, 1, 2, 3, 0,
0, 3, 2, 3, 4, 1, 3, 2, 1, 3, 1, 1, 1, 2, 1, 1, 1, 2, 3, 0,
0, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 1, 1, 2, 2, 2, 2, 2, 3, 0,
0, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 4, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
];
var tileW = 40, tileH = 40;
var mapW = 20, mapH = 20;
var currentSecond = 0, frameCount = 0, framesLastSecond = 0, lastFrameTime = 0;
var tileset = null, tilesetURL = "tileset.jpg", tilesetLoaded = false;;
var floorTypes = {
solid : 0,
path : 1,
water : 2
};
var tileTypes = {
0 : { colour:"#685b48", floor:floorTypes.solid, sprite:[{x:0,y:0,w:40,h:40}] },
1 : { colour:"#5aa457", floor:floorTypes.path, sprite:[{x:40,y:0,w:40,h:40}] },
2 : { colour:"#e8bd7a", floor:floorTypes.path, sprite:[{x:80,y:0,w:40,h:40}] },
3 : { colour:"#286625", floor:floorTypes.solid, sprite:[{x:120,y:0,w:40,h:40}] },
4 : { colour:"#678fd9", floor:floorTypes.water, sprite:[
{x:160,y:0,w:40,h:40,d:200}, {x:200,y:0,w:40,h:
40,d:200},
{x:160,y:40,w:40,h:40,d:200}, {x:200,y:40,w:40,h:40,d:200},
{x:160,y:40,w:40,h:40,d:200}, {x:200,y:0,w:40,h:40,d:200}
]}
};
var directions = {
up : 0,
right : 1,
down : 2,
left : 3
};
var keysDown = {
37 : false,
38 : false,
39 : false,
40 : false
};
var viewport = {
screen : [0,0],
startTile : [0,0],
endTile : [0,0],
offset : [0,0],
update : function(px, py) {
this.offset[0] = Math.floor((this.screen[0]/2) - px);
this.offset[1] = Math.floor((this.screen[1]/2) - py);
var tile = [ Math.floor(px/tileW), Math.floor(py/tileH) ];
this.startTile[0] = tile[0] - 1 - Math.ceil((this.screen[0]/2) / tileW);
this.startTile[1] = tile[1] - 1 - Math.ceil((this.screen[1]/2) / tileH);
if(this.startTile[0] < 0) { this.startTile[0] = 0; }
if(this.startTile[1] < 0) { this.startTile[1] = 0; }
this.endTile[0] = tile[0] + 1 + Math.ceil((this.screen[0]/2) / tileW);
this.endTile[1] = tile[1] + 1 + Math.ceil((this.screen[1]/2) / tileH);
if(this.endTile[0] >= mapW) { this.endTile[0] = mapW-1; }
if(this.endTile[1] >= mapH) { this.endTile[1] = mapH-1; }
}
};
var player = new Character();
function Character()
{
this.tileFrom = [1,1];
this.tileTo = [1,1];
this.timeMoved = 0;
this.dimensions = [30,30];
this.position = [45,45];
this.delayMove = 700;
this.direction = directions.up;
this.sprites = {};
this.sprites[directions.up] = [{x:0,y:120,w:30,h:30}];
this.sprites[directions.right] = [{x:0,y:150,w:30,h:30}];
this.sprites[directions.down] = [{x:0,y:180,w:30,h:30}];
this.sprites[directions.left] = [{x:0,y:210,w:30,h:30}];
}
Character.prototype.placeAt = function(x, y)
{
this.tileFrom = [x,y];
this.tileTo = [x,y];
this.position = [((tileW*x)+((tileW-this.dimensions[0])/2)),
((tileH*y)+((tileH-this.dimensions[1])/2))];
};
Character.prototype.processMovement = function(t)
{
if(this.tileFrom[0]==this.tileTo[0] && this.tileFrom[1]==this.tileTo[1]) { return false; }
if((t-this.timeMoved)>=this.delayMove)
{
this.placeAt(this.tileTo[0], this.tileTo[1]);
}
else
{
this.position[0] = (this.tileFrom[0] * tileW) + ((tileW-this.dimensions[0])/2);
this.position[1] = (this.tileFrom[1] * tileH) + ((tileH-this.dimensions[1])/2);
if(this.tileTo[0] != this.tileFrom[0])
{
var diff = (tileW / this.delayMove) * (t-this.timeMoved);
this.position[0]+= (this.tileTo[0]<this.tileFrom[0] ? 0 - diff : diff);
}
if(this.tileTo[1] != this.tileFrom[1])
{
var diff = (tileH / this.delayMove) * (t-this.timeMoved);
this.position[1]+= (this.tileTo[1]<this.tileFrom[1] ? 0 - diff : diff);
}
this.position[0] = Math.round(this.position[0]);
this.position[1] = Math.round(this.position[1]);
}
return true;
}
Character.prototype.canMoveTo = function(x, y)
{
if(x < 0 || x >= mapW || y < 0 || y >= mapH) { return false; }
if(tileTypes[gameMap[toIndex(x,y)]].floor!=floorTypes.path) { return false; }
return true;
};
Character.prototype.canMoveUp = function() { return this.canMoveTo(this.tileFrom[0], this.tileFrom[1]-1); };
Character.prototype.canMoveDown = function() { return this.canMoveTo(this.tileFrom[0], this.tileFrom[1]+1); };
Character.prototype.canMoveLeft = function() { return this.canMoveTo(this.tileFrom[0]-1, this.tileFrom[1]); };
Character.prototype.canMoveRight = function() { return this.canMoveTo(this.tileFrom[0]+1, this.tileFrom[1]); };
Character.prototype.moveLeft = function(t) { this.tileTo[0]-=1; this.timeMoved = t; this.direction = directions.left; };
Character.prototype.moveRight = function(t) { this.tileTo[0]+=1; this.timeMoved = t; this.direction = directions.right; };
Character.prototype.moveUp = function(t) { this.tileTo[1]-=1; this.timeMoved = t; this.direction = directions.up; };
Character.prototype.moveDown = function(t) { this.tileTo[1]+=1; this.timeMoved = t; this.direction = directions.down; };
function toIndex(x, y)
{
return((y * mapW) + x);
}
function getFrame(sprite, duration, time, animated)
{
if(!animated) { return sprite[0]; }
time = time % duration;
for(x in sprite)
{
if(sprite[x].end>=time) { return sprite[x]; }
}
}
window.onload = function()
{
ctx = document.getElementById('game').getContext("2d");
requestAnimationFrame(drawGame);
ctx.font = "bold 10pt sans-serif";
window.addEventListener("keydown", function(e) {
if(e.keyCode>=37 && e.keyCode<=40) { keysDown[e.keyCode] = true; }
});
window.addEventListener("keyup", function(e) {
if(e.keyCode>=37 && e.keyCode<=40) { keysDown[e.keyCode] = false; }
});
viewport.screen = [document.getElementById('game').width,
document.getElementById('game').height];
tileset = new Image();
tileset.onerror = function()
{
ctx = null;
alert("Failed loading tileset.");
};
tileset.onload = function() { tilesetLoaded = true; };
tileset.src = tilesetURL;
for(x in tileTypes)
{
tileTypes[x]['animated'] = tileTypes[x].sprite.length > 1 ? true : false;
if(tileTypes[x].animated)
{
var t = 0;
for(s in tileTypes[x].sprite)
{
tileTypes[x].sprite[s]['start'] = t;
t+= tileTypes[x].sprite[s].d;
tileTypes[x].sprite[s]['end'] = t;
}
tileTypes[x]['spriteDuration'] = t;
}
}
};
function drawGame()
{
if(ctx==null) { return; }
if(!tilesetLoaded) { requestAnimationFrame(drawGame); return; }
var currentFrameTime = Date.now();
var timeElapsed = currentFrameTime - lastFrameTime;
var sec = Math.floor(Date.now()/1000);
if(sec!=currentSecond)
{
currentSecond = sec;
framesLastSecond = frameCount;
frameCount = 1;
}
else { frameCount++; }
if(!player.processMovement(currentFrameTime))
{
if(keysDown[38] && player.canMoveUp()) { player.moveUp(currentFrameTime); }
else if(keysDown[40] && player.canMoveDown()) { player.moveDown(currentFrameTime); }
else if(keysDown[37] && player.canMoveLeft()) { player.moveLeft(currentFrameTime); }
else if(keysDown[39] && player.canMoveRight()) { player.moveRight(currentFrameTime); }
}
viewport.update(player.position[0] + (player.dimensions[0]/2),
player.position[1] + (player.dimensions[1]/2));
ctx.fillStyle = "#000000";
ctx.fillRect(0, 0, viewport.screen[0], viewport.screen[1]);
for(var y = viewport.startTile[1]; y <= viewport.endTile[1]; ++y)
{
for(var x = viewport.startTile[0]; x <= viewport.endTile[0]; ++x)
{
var tile = tileTypes[gameMap[toIndex(x,y)]];
var sprite = getFrame(tile.sprite, tile.spriteDuration,
currentFrameTime, tile.animated);
ctx.drawImage(tileset,
sprite.x, sprite.y, sprite.w, sprite.h,
viewport.offset[0] + (x*tileW), viewport.offset[1] + (y*tileH),
tileW, tileH);
}
}
var sprite = player.sprites[player.direction];
ctx.drawImage(tileset,
sprite[0].x, sprite[0].y, sprite[0].w, sprite[0].h,
viewport.offset[0] + player.position[0], viewport.offset[1] + player.position[1],
player.dimensions[0], player.dimensions[1]);
ctx.fillStyle = "#ff0000";
ctx.fillText("FPS: " + framesLastSecond, 10, 20);
lastFrameTime = currentFrameTime;
requestAnimationFrame(drawGame);
}
</script>
</head>
<body>
<canvas id="game" width="400" height="400"></canvas>
</body>
</html>