starfieldgame.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. function StarfieldGame() {
  2. var container = null;
  3. var canvas = null;
  4. var contextType = '2d';
  5. var contextAttributes = {};
  6. var context = null;
  7. var game = null;
  8. var starfields = [];
  9. var velocity = { x: -1, y: -1 };
  10. this.create = function (elementName, mouseBind) {
  11. game = this;
  12. container = document.getElementById(elementName);
  13. canvas = container.getElementsByTagName('canvas')[0];
  14. window.addEventListener('resize', game.handleResize);
  15. window.addEventListener('mousemove', game.handleMouseMove);
  16. window.requestAnimationFrame(game.handleRequestAnimationFrame);
  17. this.handleResize(null);
  18. };
  19. this.handleResize = function (event) {
  20. canvas.width = container.offsetWidth;
  21. canvas.height = container.offsetHeight;
  22. context = canvas.getContext(contextType, contextAttributes);
  23. context.translate(0.5, 0.5);
  24. game.init(canvas);
  25. }
  26. this.handleRequestAnimationFrame = function (event) {
  27. game.update(canvas);
  28. context.fillStyle = "#000000";
  29. context.fillRect(0, 0, canvas.width, canvas.height);
  30. game.draw(context);
  31. window.requestAnimationFrame(game.handleRequestAnimationFrame);
  32. }
  33. this.handleMouseMove = function (event) {
  34. //game.mouseMove(canvas, event.offsetX, event.offsetY);
  35. game.mouseMove(canvas, event.clientX, event.clientY);
  36. let canvasBounds = canvas.getBoundingClientRect();
  37. if (event.clientX < canvasBounds.x ||
  38. event.clientX > canvasBounds.x + canvasBounds.width ||
  39. event.clientY < canvasBounds.y ||
  40. event.clientY > canvasBounds.y + canvasBounds.height) {
  41. game.mouseMove(canvas, canvas.width / 2, event.clientY = canvas.height / 2);
  42. return;
  43. }
  44. game.mouseMove(canvas, event.clientX, event.clientY);
  45. }
  46. this.init = function (canvas) {
  47. starfields = [];
  48. for (var i = 0; i < 3; i++) {
  49. starfields.push(new Starfield());
  50. }
  51. for (var i = 0, starfield = starfields[0]; starfield = starfields[i]; i++) {
  52. starfield.init(canvas, i + 1, velocity);
  53. }
  54. };
  55. this.update = function (canvas) {
  56. for (var i = 0, starfield = starfields[0]; starfield = starfields[i]; i++) {
  57. starfield.update(canvas);
  58. }
  59. };
  60. this.draw = function (context) {
  61. for (var i = 0, starfield = starfields[0]; starfield = starfields[i]; i++) {
  62. starfield.draw(context);
  63. }
  64. };
  65. this.mouseMove = function (canvas, x, y) {
  66. for (var i = 0, starfield = starfields[0]; starfield = starfields[i]; i++) {
  67. starfield.mouseMove(canvas, x, y);
  68. }
  69. };
  70. }