Sprite Experiments
Just some messy nonsense.
HTML
<canvas id="myCanvas" width="400" height="400" >
Your browser does not support the HTML5 canvas tag.
</canvas>
CSS
canvas { border: 1px solid black; }
JavaScript
// Running Sprites
"use strict";
/*jslint browser: true, devel: true, white: true */
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
/*
0 1 2 3 4 5 6 7 8 9
123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890
*/
// UTILS
// =====
function clearCanvas() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
var g_spriteSheet;
var which = false;
function preload() {
var base = "https://notendur.hi.is/~pk/308G/images/"
g_spriteSheet = new Image();
g_spriteSheet.onload = preloadDone;
g_spriteSheet.src = which ?
base + "dude_animation_sheet.png" :
base + "walksequence_spritesheet.png"
}
function Sprite(sx, sy, width, height) {
this.sx = sx;
this.sy = sy;
this.width = width;
this.height = height;
this.image = g_spriteSheet;
}
Sprite.prototype.drawAt = function (x, y) {
ctx.drawImage(this.image,
this.sx, this.sy, this.width, this.height,
x, y, this.width, this.height);
}
var g_sprites;
function preloadDone() {
var celWidth = which ? 130 : 240;
var celHeight = which ? 150 : 295;
var numCols = which ? 7 : 6;
var numRows = which ? 4 : 5;
var numCels = which ? 27 : 30;
g_sprites = [];
var sprite;
for (var row = 0; row < numRows; ++row) {
for (var col = 0; col < numCols; ++col) {
sprite = new Sprite(col * celWidth, row * celHeight,
celWidth, celHeight)
g_sprites.push(sprite);
}
}
// Remove any superfluous ones from the end
g_sprites.splice(numCels);
console.dir(g_sprites);
main();
}
var g_cel = 0;
function main() {
clearCanvas();
ctx.fillText(""+g_cel, 10, 10);
var cel = g_sprites[g_cel]
// Primary instance
cel.drawAt(50,...