viewer.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. var lastTime = new Date().getTime();
  2. var canvas = document.getElementById("viewer");
  3. var context = canvas.getContext("2d");
  4. var atlas = new SpriteAtlas("./assets/", "sprites.xml");
  5. var currentStage;
  6. var lastFailedId = "void";
  7. let stages = [];
  8. let sets = [];
  9. let setsLoaded = [];
  10. stages.push({
  11. id: "empty",
  12. setup: () => { },
  13. update: (delta) => { },
  14. draw: (context, delta) => { },
  15. cleanup: () => { },
  16. });
  17. currentStage = stages[0];
  18. atlas.load().then(() => {
  19. resize();
  20. currentStage.setup();
  21. raf();
  22. }).catch(e => console.error(e));
  23. function raf() {
  24. let currentTime = new Date().getTime();
  25. let delta = (currentTime - lastTime) / 10;
  26. context.height = context.height;
  27. context.clearRect(0, 0, canvas.width, canvas.height);
  28. context.save();
  29. context.translate(0.5, 0.5);
  30. viewerUpdate(delta);
  31. viewerDraw(context, delta);
  32. context.restore();
  33. window.requestAnimationFrame(() => raf());
  34. lastTime = currentTime;
  35. };
  36. window.addEventListener('resize', resize);
  37. function resize(event) {
  38. let dpi = window.devicePixelRatio;
  39. canvas.width = canvas.clientWidth;
  40. canvas.height = canvas.clientHeight;
  41. context.width = canvas.clientWidth / dpi;
  42. context.height = canvas.clientHeight / dpi;
  43. context.webkitImageSmoothingEnabled = true;
  44. context.imageSmoothingEnabled = true;
  45. }
  46. function viewerUpdate(delta) {
  47. center = { x: canvas.width / 2, y: canvas.height / 2 };
  48. currentStage.update(delta);
  49. }
  50. function viewerDraw(context, delta) {
  51. context.save();
  52. context.translate(center.x, center.y);
  53. currentStage.draw(context, delta);
  54. context.restore();
  55. }
  56. function play(id) {
  57. if (currentStage && currentStage.id == id) {
  58. return;
  59. }
  60. if (currentStage) {
  61. currentStage.cleanup();
  62. }
  63. currentStage = stages.find(stage => stage.id == id);
  64. if (!currentStage) {
  65. lastFailedId = id;
  66. play("void");
  67. return;
  68. }
  69. currentStage.setup();
  70. }
  71. function getSet(setId) {
  72. let found = sets.find(set => set.id == setId);
  73. if(!found) {
  74. throw new Error("Set not found:", setId);
  75. }
  76. return found;
  77. }