"use strict"; import random from './Random'; // Bounded random number generation import Vector from './Vector'; // 2D vector class import Range from './Range'; // Range representation // 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.starSize = new Range(2, 10); // ~~~ this.canvas = canvas; this.context = canvas.getContext("2d"); this.trackWindowSize(); this.lastFrame = +new Date() / 1000; // ~~~ this.stars = []; for(let i = 0; i < 100; i++) { let nextStar = new Star( this.canvas, new Vector( random(0, this.canvas.width), random(0, this.canvas.height) ), random(this.starSize.min, this.starSize.max) ); nextStar.pointCount = random(4, 8); // Make larger stars tend towards having longer points nextStar.innerRingRatio = random(0.2, 0.8, true); nextStar.innerRingRatio = (nextStar.innerRingRatio + nextStar.innerRingRatio*(1 - (nextStar.size / this.starSize.max))) / 2; nextStar.rotation = random(0, Math.PI*2, true); nextStar.rotationStep = random(0.1, 1, true); if(random(0, 2) == 0) nextStar.rotationStep *= -1; nextStar.alpha = random(0.2, 0.9, true); this.stars.push(nextStar); } } 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()) / 1000; this.currentDt = this.currentFrame - this.lastFrame; // Update all the stars for(let star of this.stars) star.update(this.currentDt); this.lastFrame = this.currentFrame; } 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; });