1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374 |
- function AssetLoader() {
- var assetCache = {};
- var spriteCache = {};
- var loaded = {};
- var self = this;
- this.load = function(files, callback) {
- //TODO: display loading bar/spinner
- for(var key in files) {
- var filename = files[key];
- this.loadImage(key, files[key], callback);
- }
- }
- this.loadImage = function(key, filename, callback) {
- var image = new Image();
- loaded[key] = false;
- image.onload = function() {
- self.loadComplete(key, callback);
- };
- image.src = filename;
- assetCache[key] = image;
- };
- this.loadComplete = function(key, callback) {
- loaded[key] = true;
- if(self.areLoaded()) {
- //TODO: remove loading bar/spinner
- callback();
- }
- };
- this.areLoaded = function() {
- for(var key in loaded) {
- if(!loaded[key]) {
- return false;
- }
- }
- return true;
- };
- this.getSpriteByCoords = function(spriteName, sheetName, position, size) {
- if(!spriteCache.hasOwnProperty(spriteName)) {
- var canvas = document.createElement("canvas");
- canvas.width = size.width;
- canvas.height = size.height;
- var context = canvas.getContext('2d');
- context.drawImage(assetCache[sheetName], position.x, position.y, size.width, size.height, 0, 0, size.width, size.height);
- spriteCache[spriteName] = canvas;
- }
- return spriteCache[spriteName];
- };
- this.buildSprite = function(spriteName, sheetName, position, size) {
- var canvas = document.createElement("canvas");
- canvas.width = size.width;
- canvas.height = size.height;
- var context = canvas.getContext('2d');
- context.drawImage(assetCache[sheetName], position.x, position.y, size.width, size.height, 0, 0, size.width, size.height);
- spriteCache[spriteName] = canvas;
- };
- this.getSprite = function(spriteName) {
- if(!spriteCache.hasOwnProperty(spriteName)) {
- console.warn("Sprite '" + spriteName +"' not defined. Please call buildSprite() before using this function.");
- return new Image();
- }
- return spriteCache[spriteName];
- }
- this.calculatePosition = function(tilex, tiley) {
- return {x: tilex * 16, y: tiley * 16};
- }
- };
|