assetloader.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. function AssetLoader() {
  2. var assetCache = {};
  3. var spriteCache = {};
  4. var loaded = {};
  5. var self = this;
  6. this.load = function(files, callback) {
  7. //TODO: display loading bar/spinner
  8. for(var key in files) {
  9. var filename = files[key];
  10. this.loadImage(key, files[key], callback);
  11. }
  12. }
  13. this.loadImage = function(key, filename, callback) {
  14. var image = new Image();
  15. loaded[key] = false;
  16. image.onload = function() {
  17. self.loadComplete(key, callback);
  18. };
  19. image.src = filename;
  20. assetCache[key] = image;
  21. };
  22. this.loadComplete = function(key, callback) {
  23. loaded[key] = true;
  24. if(self.areLoaded()) {
  25. //TODO: remove loading bar/spinner
  26. callback();
  27. }
  28. };
  29. this.areLoaded = function() {
  30. for(var key in loaded) {
  31. if(!loaded[key]) {
  32. return false;
  33. }
  34. }
  35. return true;
  36. };
  37. this.getSpriteByCoords = function(spriteName, sheetName, position, size) {
  38. if(!spriteCache.hasOwnProperty(spriteName)) {
  39. var canvas = document.createElement("canvas");
  40. canvas.width = size.width;
  41. canvas.height = size.height;
  42. var context = canvas.getContext('2d');
  43. context.drawImage(assetCache[sheetName], position.x, position.y, size.width, size.height, 0, 0, size.width, size.height);
  44. spriteCache[spriteName] = canvas;
  45. }
  46. return spriteCache[spriteName];
  47. };
  48. this.buildSprite = function(spriteName, sheetName, position, size) {
  49. var canvas = document.createElement("canvas");
  50. canvas.width = size.width;
  51. canvas.height = size.height;
  52. var context = canvas.getContext('2d');
  53. context.drawImage(assetCache[sheetName], position.x, position.y, size.width, size.height, 0, 0, size.width, size.height);
  54. spriteCache[spriteName] = canvas;
  55. };
  56. this.getSprite = function(spriteName) {
  57. if(!spriteCache.hasOwnProperty(spriteName)) {
  58. console.warn("Sprite '" + spriteName +"' not defined. Please call buildSprite() before using this function.");
  59. return new Image();
  60. }
  61. return spriteCache[spriteName];
  62. }
  63. this.calculatePosition = function(tilex, tiley) {
  64. return {x: tilex * 16, y: tiley * 16};
  65. }
  66. };