Starfield
by nynexman4464
HTML
<canvas id="canvas">You have an old browser.</canvas>
CSS
body{margin:0;overflow:hidden;}
JavaScript
let width, height;
function setupCanvas(canvas) {
width = canvas.width = window.innerWidth;
height = canvas.height = window.innerHeight;
canvas.style.width = canvas.width + 'px';
canvas.style.height = canvas.height + 'px';
// Get the device pixel ratio, falling back to 1.
var dpr = window.devicePixelRatio || 1;
// Get the size of the canvas in CSS pixels.
var rect = canvas.getBoundingClientRect();
console.log(dpr, rect, height, width);
// Give the canvas pixel dimensions of their CSS
// size * the device pixel ratio.
width = canvas.width = rect.width * dpr;
height = canvas.height = rect.height * dpr;
var ctx = canvas.getContext('2d');
// Scale all drawing operations by the dpr, so you
// don't have to worry about the difference.
// ctx.scale(dpr, dpr);
return ctx;
}
window.addEventListener('resize', () => {
setupCanvas(canvas)
});
const canvas = document.getElementById("canvas");
const context = setupCanvas(canvas);
const maxStars = 2000;
const maxDepth = 255;
const stars = Array(maxStars).fill(0).map((_, i) => [Math.random(), Math.random() * maxDepth, Math.random() * width]);
let i = 0;
context.fillRect(0, 0, width, height);
function doit() {
window.requestAnimationFrame(() => {
context.fillStyle = "black";
context.fillRect(0, 0, width, height);
context.fillStyle = "white";
stars.forEach(([angle, start, offset], j) => {
// move to center
context.translate(width / 2, height / 2);
// rotate
const rot = angle * 2 * Math.PI;
context.rotate(rot);
// move by offset
context.translate(offset, offset);
// draw circle
context.beginPath();
context.arc(start * width / maxDepth, start * width / maxDepth, 20 * start / maxDepth, 0, 2 * Math.PI);
//console.log(angle, start);
context.fill();
// update star
stars[j] = (start > (maxDepth + Math.random() * 5)) ? [Math.random(), 0, offset] : [angle, start + Math.log(Math.max(1.1,start)),...