Background.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. class Background {
  2. constructor() {
  3. this.bounds = { width: 2000, height: 500 };
  4. this.offset = { x: -2000, y: -500 };
  5. this.velocity = { x: 0.015, y: 0.005 };
  6. this.screensizeMultiplier = 2;
  7. this.grid = [];
  8. }
  9. init() {
  10. this.handleResize();
  11. this.generateStarfield();
  12. }
  13. generateStarfield() {
  14. this.layers = [];
  15. for (let l = 0; l < 3; l++) {
  16. let field = {
  17. stars: [],
  18. position: {
  19. x: 0,
  20. y: 0
  21. },
  22. depth: (l + 1) * 0.15
  23. };
  24. for (let i = 0; i < 100; i++) {
  25. let star = {};
  26. star.x = Math.floor(this.bounds.width * Math.random());
  27. star.y = Math.floor(this.bounds.height * Math.random());
  28. star.r = Math.floor(3 * Math.random() + 2);
  29. field.stars.push(star);
  30. }
  31. this.layers.push(field);
  32. }
  33. }
  34. draw(context, delta) {
  35. context.fillStyle = "#AAAAAA";
  36. context.lineWidth = 1;
  37. context.save();
  38. context.translate(this.offset.x, this.offset.y);
  39. for (let layerIndex in this.layers) {
  40. let field = this.layers[layerIndex];
  41. field.position.x -= (layerIndex + 1) * this.velocity.x;
  42. field.position.y -= (layerIndex + 1) * this.velocity.y;
  43. field.position.x %= this.bounds.width;
  44. field.position.y %= this.bounds.height;
  45. for (let gridIndex in this.grid) {
  46. let gridLocation = this.grid[gridIndex];
  47. context.save();
  48. context.translate(
  49. (gridLocation[0] * this.bounds.width) + field.position.x,
  50. (gridLocation[1] * this.bounds.height) + field.position.y);
  51. for (let starIndex in field.stars) {
  52. let star = field.stars[starIndex];
  53. context.beginPath();
  54. context.arc(star.x, star.y, field.depth * star.r, 0, 2 * Math.PI);
  55. context.fill();
  56. }
  57. context.restore();
  58. }
  59. }
  60. context.restore();
  61. }
  62. handleResize() {
  63. if (canvas.width > this.bounds.width * this.screensizeMultiplier ||
  64. canvas.width < this.bounds.width * this.screensizeMultiplier - 1) {
  65. this.screensizeMultiplier = Math.ceil(canvas.width / this.bounds.width) + 1;
  66. this.grid = [];
  67. for (let gridX = 0; gridX < this.screensizeMultiplier; gridX++) {
  68. for (let gridY = 0; gridY < this.screensizeMultiplier; gridY++) {
  69. this.grid.push([gridX, gridY]);
  70. }
  71. }
  72. }
  73. this.offset.x = -(this.bounds.width * Math.floor(this.screensizeMultiplier / 2)) + (canvas.width / 2);
  74. this.offset.y = -(this.bounds.height * Math.floor(this.screensizeMultiplier / 2)) + (canvas.height / 2);
  75. }
  76. move(direction) {
  77. this.velocity.x = direction.x;
  78. this.velocity.y = direction.y;
  79. }
  80. }