You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

SpriteSheet.js 1.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. export default class SpriteSheet {
  2. constructor(url, tilew, tileh, scale = 1) {
  3. this.url = url;
  4. this.tilew = tilew;
  5. this.tileh = tileh;
  6. this.scale = scale;
  7. this.definitions = {};
  8. this.waiting = [];
  9. this.ready = false;
  10. this.img = new Image();
  11. this.img.src = url;
  12. this.img.onload = () => {
  13. this.ready = true;
  14. this.waiting.forEach(f => f());
  15. };
  16. }
  17. whenReady(fn) {
  18. if (this.ready) return fn();
  19. this.waiting.push(fn);
  20. return this;
  21. }
  22. define(name, x, y, w = this.tilew, h = this.tileh) {
  23. this.definitions[name] = null;
  24. this.whenReady(() => {
  25. let can = document.createElement("canvas");
  26. can.width = w * this.scale;
  27. can.height = h * this.scale;
  28. let ctx = can.getContext("2d");
  29. ctx.mozImageSmoothingEnabled = false;
  30. ctx.webkitImageSmoothingEnabled = false;
  31. ctx.msImageSmoothingEnabled = false;
  32. ctx.imageSmoothingEnabled = false;
  33. ctx.drawImage(
  34. this.img, x, y,
  35. w, h, 0, 0,
  36. w * this.scale, h * this.scale);
  37. this.definitions[name] = can;
  38. });
  39. return this;
  40. }
  41. defineTile(name, tx, ty) {
  42. return this.define(name, tx * this.tilew, ty * this.tileh);
  43. }
  44. draw(ctx, name, x, y, sx = 1, sy = 1) {
  45. let def = this.definitions[name];
  46. if (def === null) return;
  47. if (def === undefined) throw new Error("Undefined sprite: "+name);
  48. ctx.drawImage(
  49. def, x, y,
  50. def.width * sx,
  51. def.height * sy);
  52. return this;
  53. }
  54. drawTile(ctx, name, tx, ty, sx = 1, sy = 1) {
  55. this.draw(
  56. ctx, name,
  57. tx * this.tilew * this.scale, ty * this.tileh * this.scale,
  58. sx, sy);
  59. return this;
  60. }
  61. get tileWidth() {
  62. return this.tilew * this.scale;
  63. }
  64. get tileHeight() {
  65. return this.tileh * this.scale;
  66. }
  67. }