From 93e3578a7a1f1f2ce77273ec73121b616aac58c7 Mon Sep 17 00:00:00 2001 From: Greg Shuflin Date: Wed, 25 Oct 2023 03:18:50 -0700 Subject: [PATCH] Add reference code --- src/starfield/starfield.ts | 82 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) diff --git a/src/starfield/starfield.ts b/src/starfield/starfield.ts index 4c23160..5f0286c 100644 --- a/src/starfield/starfield.ts +++ b/src/starfield/starfield.ts @@ -14,3 +14,85 @@ function resize() { } window.addEventListener('resize', resize, false); + + +function reference() { +let middle = { x: canvas.width / 2, y: canvas.height / 2 } + +// Each star is stored as an { x, y } object representing +// its offset from the middle of the screen + +function canvasStarPosition(star) { + return { x: middle.x + star.x, + y: middle.y + star.y } +} + +function starSize(star) { + // Size is proportional to distance from the middle + return Math.max(Math.abs(star.x), Math.abs(star.y)) / 100 +} + +function drawStar(ctx, star) { + let { x, y } = canvasStarPosition(star) + let r = starSize(star) + ctx.fillStyle = 'white' + ctx.beginPath() + ctx.arc(x, y, r, 0, 2*Math.PI) + ctx.fill() +} + +let start = 0 +let stars = [] +let timeSinceLastStar = Infinity +let starInterval = 10000 // milliseconds + +function makeStar() { + let angle = Math.random() * 2*Math.PI + stars.push({ + x : Math.cos(angle), + y : Math.sin(angle), + // The multiplier affects how quickly the star moves. + // Varying this makes some stars appear closer (faster + // movement), some further (slower movement). + multiplier : 1.01 + Math.random() * 0.04 + }) +} + +function step(timestamp) { + if (!start) start = timestamp + var progress = timestamp - start + + // Create a new star if it's been long enough since + // the previous one + timeSinceLastStar += progress + if (timeSinceLastStar > starInterval) { + timeSinceLastStar = 0 + makeStar() + } + + // Clear the screen. + // If you want the hyperspace effect, skip this. + ctx.clearRect(0,0,canvas.width, canvas.height) + + stars.forEach((s) => { + // Increase the star's distance from the middle + // proportionally to its current distance + s.x *= s.multiplier + s.y *= s.multiplier + drawStar(ctx, s) + }) + + // Remove stars outside the view boundary + let i = stars.length; + while (--i) { + let {x, y} = canvasStarPosition(stars[i]) + if (x < 0 || x > canvas.width || y < 0 || y > canvas.height) { + stars.splice(i, 1) + } + } + window.requestAnimationFrame(step) +} +window.requestAnimationFrame(step) +} + +reference();