Starfield: More color options

This commit is contained in:
Greg Shuflin 2023-10-27 02:39:57 -07:00
parent 89a963e30b
commit 3e834efb3a

View File

@ -1,4 +1,5 @@
import { reference } from "./reference.ts"
import * as dat from "dat.gui";
const canvas = document.querySelector("#mainCanvas");
const ctx = canvas.getContext("2d");
@ -10,6 +11,10 @@ canvas.width = cw * dpr;
canvas.height = ch * dpr;
ctx.scale(dpr, dpr);
function random(min, max) {
return min + Math.random() * ( max - min );
}
function resize() {
canvas.width = window.innerWidth * dpr;
canvas.height = window.innerHeight * dpr;
@ -24,6 +29,7 @@ class Star {
this.x = x;
this.y = y;
this.multiplier = multiplier;
this.color = random(0, 360);
}
canvasPos() {
@ -40,15 +46,28 @@ class Star {
return 1.0;
}
render(ctx) {
render(ctx, style) {
const { x, y } = this.canvasPos();
const r = this.size();
ctx.fillStyle = "red";
ctx.fillStyle = this.computeStyle(style);
ctx.beginPath();
ctx.arc(x, y, r, 0, 2*Math.PI)
ctx.fill();
}
private computeStyle(style) {
if (style == "white") {
return "white";
}
if (style == "red") {
return "red";
}
if (style == "multi") {
return `hsl(${this.color}, 100%, 50%)`;
}
}
static make() {
const angle = Math.random() * 2*Math.PI
const x = Math.cos(angle);
@ -67,12 +86,17 @@ const state = {
timeSinceLastStar: Infinity,
};
let start = null;
let stars = [];
let timeSinceLastStar = Infinity;
const starIntervalms = 2000;
const fadeout = 8 / 100;
const options = {
fadeout: 8/100,
starIntervalMS: 2000,
starStyle: "white",
}
const controls = new dat.GUI({name: "Controls", closed: false});
controls.add(options, "fadeout").min(0).max(1).step(0.01).name("Fadeout");
controls.add(options, "starIntervalMS").min(500).max(50000).step(500).name("Star Interval");
controls.add(options, "starStyle").options({"White": "white", "Red":"red", "Multi": "multi"}).name("Style");
function clear(ctx, alpha) {
ctx.globalCompositeOperation = "destination-out";
@ -90,14 +114,14 @@ function loop(timestamp) {
// Create a new star if it's been long enough since
// the previous one
state.timeSinceLastStar += progress;
if (state.timeSinceLastStar > starIntervalms) {
if (state.timeSinceLastStar > options.starIntervalMS) {
state.timeSinceLastStar = 0
state.stars.push(Star.make());
}
// Clear the screen.
// If you want the hyperspace effect, skip this.
clear(ctx, fadeout);
clear(ctx, options.fadeout);
state.stars.forEach((star) => {
// Increase the star's distance from the middle
@ -105,7 +129,7 @@ function loop(timestamp) {
const multiplier = star.multiplier;
star.x *= multiplier
star.y *= multiplier
star.render(ctx);
star.render(ctx, options.starStyle);
})
// Remove stars outside the view boundary