"use strict"; import random from './Random'; // Bounded random number generation import Vector from './Vector'; // 2D vector class // Subclasses import Star from './Star'; // ~~~ class StarlightRenderer { constructor(canvas) { // The colour of the sky in the background. this.skyColour = "hsla(248, 100%, 23%, 1)"; // ~~~ this.canvas = canvas; this.context = canvas.getContext("2d"); this.trackWindowSize(); this.lastFrame = new Date(); // ~~~ this.stars = []; for(let i = 0; i < 100; i++) { this.stars.push(new Star( this.canvas, new Vector( random(0, this.canvas.width), random(0, this.canvas.height) ), random(0, 10) )); } } nextFrame() { this.update(); this.render(this.canvas, this.context); requestAnimationFrame(this.nextFrame.bind(this)); } update() { // Calculate the time between this frame and the last one this.currentFrame = new Date(); this.currentDt = this.currentFrame - this.lastFrame; // Stars for(let star of this.stars) star.update(this.currentDt); } render(canvas, context) { // Background context.fillStyle = this.skyColour; context.fillRect(0, 0, this.canvas.width, this.canvas.height); // Stars for(let star of this.stars) star.render(context); } /** * Updates the canvas size to match the current viewport size. */ matchWindowSize() { this.canvas.width = window.innerWidth; this.canvas.height = window.innerHeight; //this.render(this.context); } /** * Makes the canvas size track the window size. */ trackWindowSize() { this.matchWindowSize(); window.addEventListener("resize", this.matchWindowSize.bind(this)); } } window.addEventListener("load", function (event) { var canvas = document.getElementById("canvas-main"), renderer = new StarlightRenderer(canvas); renderer.nextFrame(); window.renderer = renderer; });