class Background { constructor() { this.bounds = { width: 2000, height: 500 }; this.offset = { x: -2000, y: -500 }; this.velocity = { x: 0.015, y: 0.005 }; this.screensizeMultiplier = 2; this.grid = []; } init() { this.handleResize(); this.generateStarfield(); } generateStarfield() { this.layers = []; for (let l = 0; l < 3; l++) { let field = { stars: [], position: { x: 0, y: 0 }, depth: (l + 1) * 0.15 }; for (let i = 0; i < 100; i++) { let star = {}; star.x = Math.floor(this.bounds.width * Math.random()); star.y = Math.floor(this.bounds.height * Math.random()); star.r = Math.floor(3 * Math.random() + 2); field.stars.push(star); } this.layers.push(field); } } draw(context, delta) { context.fillStyle = "#AAAAAA"; context.lineWidth = 1; context.save(); context.translate(this.offset.x, this.offset.y); for (let layerIndex in this.layers) { let field = this.layers[layerIndex]; field.position.x -= (layerIndex + 1) * this.velocity.x; field.position.y -= (layerIndex + 1) * this.velocity.y; field.position.x %= this.bounds.width; field.position.y %= this.bounds.height; for (let gridIndex in this.grid) { let gridLocation = this.grid[gridIndex]; context.save(); context.translate( (gridLocation[0] * this.bounds.width) + field.position.x, (gridLocation[1] * this.bounds.height) + field.position.y); for (let starIndex in field.stars) { let star = field.stars[starIndex]; context.beginPath(); context.arc(star.x, star.y, field.depth * star.r, 0, 2 * Math.PI); context.fill(); } context.restore(); } } context.restore(); } handleResize() { if (canvas.width > this.bounds.width * this.screensizeMultiplier || canvas.width < this.bounds.width * this.screensizeMultiplier - 1) { this.screensizeMultiplier = Math.ceil(canvas.width / this.bounds.width) + 1; this.grid = []; for (let gridX = 0; gridX < this.screensizeMultiplier; gridX++) { for (let gridY = 0; gridY < this.screensizeMultiplier; gridY++) { this.grid.push([gridX, gridY]); } } } this.offset.x = -(this.bounds.width * Math.floor(this.screensizeMultiplier / 2)) + (canvas.width / 2); this.offset.y = -(this.bounds.height * Math.floor(this.screensizeMultiplier / 2)) + (canvas.height / 2); } move(direction) { this.velocity.x = direction.x; this.velocity.y = direction.y; } }