Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

Texture.js 1.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import Rect from "./Rect.js";
  2. import assets from "./assets.js";
  3. export default class Texture {
  4. constructor(sheet, nestedArr) {
  5. this.sheet = sheet;
  6. this.nestedArr = nestedArr;
  7. this.can = document.createElement("canvas");
  8. this.ctx = this.can.getContext("2d");
  9. this.width = 0;
  10. this.height = 0;
  11. this.sheet.whenReady(() => this.init());
  12. }
  13. findWidthHeight(arr) {
  14. arr.forEach(e => {
  15. if (e instanceof Array) {
  16. this.findWidthHeight(e);
  17. } else {
  18. let right = (e.x + 1) * this.sheet.tileWidth;
  19. let bottom = (e.y + 1) * this.sheet.tileHeight;
  20. if (right > this.width)
  21. this.width = right;
  22. if (bottom > this.height)
  23. this.height = bottom;
  24. }
  25. });
  26. }
  27. fillCanvas(arr) {
  28. arr.forEach(e => {
  29. if (e instanceof Array) {
  30. this.fillCanvas(e);
  31. } else {
  32. this.sheet.drawTile(this.ctx, e.name, e.x, e.y);
  33. }
  34. });
  35. }
  36. init() {
  37. this.findWidthHeight(this.nestedArr);
  38. this.can.width = this.width;
  39. this.can.height = this.height;
  40. this.fillCanvas(this.nestedArr);
  41. }
  42. draw(ctx, x, y) {
  43. ctx.drawImage(this.can, x, y, this.width, this.height);
  44. }
  45. drawAt(ctx, vec) {
  46. this.draw(ctx, vec.pixelX, vec.pixelY);
  47. }
  48. }