system.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. function System() {
  2. var container = null;
  3. var canvas = null;
  4. var contextType = '2d';
  5. var contextAttributes = {};
  6. var context = null;
  7. var system = null;
  8. var game = null;
  9. var backgroundColor = "#D3D3D3";
  10. var framerate = 60;
  11. var lastTime = 0;
  12. this.create = function(elementName, gameObject, defaultBackgroundColor) {
  13. system = this;
  14. game = gameObject;
  15. backgroundColor = defaultBackgroundColor || backgroundColor;
  16. container = document.getElementById(elementName);
  17. canvas = document.createElement("canvas");
  18. container.appendChild(canvas);
  19. window.addEventListener('resize', system.handleResize);
  20. canvas.addEventListener('mousemove', system.handleMouseMove);
  21. canvas.addEventListener('mousedown', system.handleMouseClick);
  22. canvas.addEventListener('contextmenu', system.handleContextMenu);
  23. canvas.addEventListener('touchstart', system.handleMouseClick);
  24. system.handleResize(null);
  25. game.init(system, canvas);
  26. window.requestAnimationFrame(system.handleRequestAnimationFrame);
  27. };
  28. this.handleResize = function(event) {
  29. canvas.width = container.offsetWidth;
  30. canvas.height = container.offsetHeight;
  31. context = canvas.getContext(contextType, contextAttributes);
  32. context.translate(0.5, 0.5);
  33. };
  34. this.handleRequestAnimationFrame = function(event) {
  35. var currentTime = new Date().getTime();
  36. var delta = (currentTime - lastTime) / (1000 / framerate);
  37. if(delta > 100) {
  38. delta = 1;
  39. }
  40. game.updateDelta(canvas, delta);
  41. lastTime = currentTime;
  42. context.fillStyle = backgroundColor;
  43. context.fillRect(0 ,0, canvas.width, canvas.height);
  44. game.draw(context);
  45. window.requestAnimationFrame(system.handleRequestAnimationFrame);
  46. };
  47. this.handleMouseMove = function(event) {
  48. game.mouseMove(canvas, event.offsetX, event.offsetY);
  49. };
  50. this.handleMouseClick = function(event) {
  51. game.mouseClick(canvas, event.button, event.offsetX, event.offsetY);
  52. };
  53. this.handleContextMenu = function(event) {
  54. game.contextMenu(canvas, event);
  55. event.preventDefault();
  56. };
  57. }