SpriteAtlas.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. class SpriteAtlas {
  2. constructor(xmlFilename) {
  3. this.xmlFilename = xmlFilename;
  4. this.atlas = {};
  5. this.spritesheetImage = new Image();
  6. this.cacheBusting = true;
  7. }
  8. load() {
  9. return new Promise((resolve, reject) => {
  10. var request = new XMLHttpRequest();
  11. request.addEventListener("load", (event) => this.xmlLoadComplete(event, resolve, reject));
  12. let url = this.xmlFilename;
  13. if (this.cacheBusting) {
  14. url += "?v=" + new Date().getTime();
  15. }
  16. request.open("GET", url);
  17. request.setRequestHeader("Content-Type", "text/xml");
  18. request.send();
  19. });
  20. }
  21. xmlLoadComplete(event, resolve, reject) {
  22. var source = (new DOMParser()).parseFromString(event.target.responseText, "application/xml");
  23. var textureAtlas = source.getElementsByTagName("TextureAtlas")[0];
  24. this.populateAtlas(source);
  25. var sheetsrc = `./assets/${textureAtlas.getAttribute("imagePath")}`;
  26. if (this.cacheBusting) {
  27. sheetsrc += "?v=" + new Date().getTime();
  28. }
  29. this.spritesheetImage.src = sheetsrc;
  30. this.spritesheetImage.addEventListener('load', resolve);
  31. };
  32. populateAtlas(source) {
  33. var subtextures = source.getElementsByTagName("SubTexture");
  34. for (var i = 0, subtexture = subtextures[0]; subtexture = subtextures[i]; i++) {
  35. this.atlas[subtexture.getAttribute("name")] = {
  36. x: parseInt(subtexture.getAttribute("x")),
  37. y: parseInt(subtexture.getAttribute("y")),
  38. width: parseInt(subtexture.getAttribute("width")),
  39. height: parseInt(subtexture.getAttribute("height"))
  40. };
  41. }
  42. };
  43. drawCentered(context, name, position) {
  44. var imageLookup = this.atlas[name];
  45. context.drawImage(this.spritesheetImage,
  46. imageLookup.x,
  47. imageLookup.y,
  48. imageLookup.width,
  49. imageLookup.height,
  50. position.x - imageLookup.width / 2,
  51. position.y - imageLookup.height / 2,
  52. imageLookup.width,
  53. imageLookup.height);
  54. };
  55. drawBottomCentered(context, name, position) {
  56. var imageLookup = this.atlas[name];
  57. context.drawImage(this.spritesheetImage,
  58. imageLookup.x,
  59. imageLookup.y,
  60. imageLookup.width,
  61. imageLookup.height,
  62. position.x - imageLookup.width / 2,
  63. position.y + imageLookup.height / 2,
  64. imageLookup.width,
  65. imageLookup.height);
  66. };
  67. getWidth(name) {
  68. return this.atlas[name].width;
  69. };
  70. getHeight(name) {
  71. return this.atlas[name].height;
  72. };
  73. }