System.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. class System {
  2. constructor() {
  3. this.lastTime = 0;
  4. }
  5. attach(game, canvas) {
  6. game.init(canvas);
  7. window.addEventListener('resize', (event) => this.handleResize(event));
  8. this.handleResize(null);
  9. window.addEventListener("deviceorientation", (event) => this.handleOrientation(event));
  10. window.requestAnimationFrame(() => this.raf());
  11. }
  12. ajaxGet(url, headers) {
  13. return new Promise((resolve, reject) => {
  14. var request = new XMLHttpRequest();
  15. request.open("GET", url, true);
  16. request.onreadystatechange = (response) => {
  17. if (request.readyState != 4 || request.status != 200) return;
  18. resolve(request.responseText);
  19. };
  20. for (let key in headers) {
  21. request.setRequestHeader(key, headers[key]);
  22. }
  23. request.send();
  24. });
  25. }
  26. async jsonGet(url, headers) {
  27. let jsonObject = await this.ajaxGet(url, headers);
  28. return JSON.parse(jsonObject);
  29. }
  30. handleResize(event) {
  31. let dpi = this.getDpi();
  32. canvas.width = canvas.clientWidth * dpi;
  33. canvas.height = canvas.clientHeight * dpi;
  34. this.context = canvas.getContext('2d');
  35. this.context.webkitImageSmoothingEnabled = true;
  36. this.context.imageSmoothingEnabled = true;
  37. game.handleResize(event);
  38. };
  39. getDpi() {
  40. return Math.min(2, window.devicePixelRatio);
  41. }
  42. raf() {
  43. let currentTime = new Date().getTime();
  44. let delta = (currentTime - this.lastTime) / 10;
  45. this.context.clearRect(0, 0, canvas.width, canvas.height);
  46. this.context.save();
  47. this.context.translate(0.5, 0.5);
  48. game.draw(this.context, delta);
  49. this.context.restore();
  50. window.requestAnimationFrame(() => this.raf());
  51. this.lastTime = currentTime;
  52. };
  53. handleOrientation(event) {
  54. //this.game.handleOrientation(event);
  55. }
  56. }