SpritesheetAtlas.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import { Rectangle } from './spatial/Rectangle.js'
  2. export class DrawableSprite {
  3. constructor(atlas, bounds) {
  4. this.atlas = atlas
  5. this.bounds = bounds
  6. }
  7. draw(ctx, scaledCanvas) {
  8. if(!this.atlas.isLoaded()) {
  9. ctx.strokeStyle = "#EE4444"
  10. ctx.beginPath()
  11. ctx.rect(-this.bounds.width / 2, -this.bounds.height / 2, this.bounds.width, this.bounds.height)
  12. ctx.stroke()
  13. return
  14. }
  15. ctx.drawImage(this.atlas.spritesheetImage,
  16. this.bounds.x,
  17. this.bounds.y,
  18. this.bounds.width,
  19. this.bounds.height,
  20. -this.bounds.width / 2,
  21. -this.bounds.height / 2,
  22. this.bounds.width,
  23. this.bounds.height);
  24. }
  25. getGridPosition() {
  26. return [
  27. this.bounds.x / (this.atlas.tileDimensions.width + this.atlas.tileDimensions.margin),
  28. this.bounds.y / (this.atlas.tileDimensions.height + this.atlas.tileDimensions.margin),
  29. ]
  30. }
  31. }
  32. export class SpritesheetAtlas {
  33. constructor() {
  34. this.loaded = false;
  35. this.spritesheetImage = new Image()
  36. this.assetsPath = "";
  37. this.tileDimensions = {width: 16, height: 16, margin: 0}
  38. this.spriteCache = {}
  39. this.bounds = {width: 0, height: 0}
  40. }
  41. async load(assetsPath, tileDimensions) {
  42. this.assetsPath = assetsPath;
  43. this.tileDimensions = tileDimensions
  44. let loadPromise = this.imageLoadComplete();
  45. this.bounds = {
  46. width: this.spritesheetImage.width / (tileDimensions.width + tileDimensions.margin),
  47. height: this.spritesheetImage.height / (tileDimensions.height + tileDimensions.margin)
  48. }
  49. this.loaded = true
  50. return await loadPromise
  51. }
  52. imageLoadComplete() {
  53. return new Promise((resolve, reject) => {
  54. this.spritesheetImage.src = this.assetsPath;
  55. this.spritesheetImage.addEventListener('load', resolve);
  56. this.spritesheetImage.addEventListener('error', reject);
  57. });
  58. };
  59. isLoaded() {
  60. return this.loaded
  61. }
  62. getDrawableSprite(x, y) {
  63. if(!this.spriteCache[`${x},${y}`]) {
  64. this.spriteCache[`${x},${y}`] = new DrawableSprite(this, new Rectangle(x * this.tileDimensions.width + x * this.tileDimensions.margin, y * this.tileDimensions.height + y * this.tileDimensions.margin, this.tileDimensions.width, this.tileDimensions.height))
  65. }
  66. return this.spriteCache[`${x},${y}`]
  67. }
  68. }