ZeldaFun

by Ben Watts

HTML

<canvas id="canvas" width="160" height="160">
    Sorry but your browser doesn't support the canvas tag.
</canvas>

JavaScript

var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var spriteSheet = new Image();
spriteSheet.src = "http://www.purezc.net/Tiles/t3s1.gif";

function block(xPos, yPos, spriteWidth, spriteHeight)
{
    this.XPos = xPos;
    this.YPos = yPos;
    this.SpriteWidth = spriteWidth;
    this.SpriteHeight = spriteHeight;
}

var tiles = new Array();

var ySprite = (Math.random() % 4) + 1;

tiles.push(new block(0,0,3,ySprite));
tiles.push(new block(16,0,3,ySprite));
tiles.push(new block(32,0,1,ySprite));
tiles.push(new block(48,0,1,ySprite));
tiles.push(new block(64,0,1,ySprite));
tiles.push(new block(80,0,1,ySprite));
tiles.push(new block(96,0,1,ySprite));
tiles.push(new block(112,0,1,ySprite));
tiles.push(new block(128,0,1,ySprite));
tiles.push(new block(144,0,2,ySprite));

var intervalID = -1;
var QueueNewFrame = function () {
    if (window.requestAnimationFrame)
        window.requestAnimationFrame(renderingLoop);
    else if (window.msRequestAnimationFrame)
        window.msRequestAnimationFrame(renderingLoop);
    else if (window.webkitRequestAnimationFrame)
        window.webkitRequestAnimationFrame(renderingLoop);
    else if (window.mozRequestAnimationFrame)
        window.mozRequestAnimationFrame(renderingLoop);
    else if (window.oRequestAnimationFrame)
        window.oRequestAnimationFrame(renderingLoop);
    else {
        QueueNewFrame = function () {
        };
        intervalID = window.setInterval(renderingLoop, 16.7);
    }
};

var renderingLoop = function () {
    context.style = "#000";
    context.fillRect(0, 0, canvas.width, canvas.height);

    // Draw tiles
    for(i = 0;i < tiles.length; i++)
    {
        var tile = tiles[i];
        context.drawImage(spriteSheet, 16 * tile.SpriteWidth, 16 * tile.SpriteHeight, 16, 16, tile.XPos, tile.YPos, 16, 16);
    }
    
    QueueNewFrame();
};

window.setInterval(renderingLoop, 16.7);