Nice galaxy background
Nice space background in minimal javascript
by Marcel
HTML
<button id="b">
Generate another
</button>
<canvas id="c" width="1366" height="768"></canvas>
JavaScript
// import { randInt, degToRad } from "kontra"
// Based on this article
// https://martinstellinga.com/uncategorized/generating-a-starscape/
// There is javascript source code for that generator, but there is just way too much code there
// This is a rough approximation of the same steps
// kontra.js has these functions as well.
const randInt = (min, max) => ((Math.random() * (max - min + 1)) | 0) + min
const degToRad = d => (Math.PI/180)*d
// pick random item in list
const pick = (list) => list[randInt(0, list.length - 1)]
// calc distance between two points
const distance = (x1, y1, x2, y2) => Math.hypot(x2-x1, y2-y1)
const drawCircle = (ctx, x, y, r, colour, alpha) => {
ctx.globalAlpha = alpha;
ctx.fillStyle = colour;
ctx.beginPath();
ctx.arc(x, y, r, 0, degToRad(360), 0);
ctx.fill();
}
// create a canvas element and context of the specified size
const createCanvas = (w, h) => {
const canvas = document.createElement('canvas')
canvas.width = w
canvas.height = h
const ctx = canvas.getContext('2d')
return [ctx, canvas]
}
const colours = [
'#0069aa',
'#ca52c9',
'#ea323c'
]
const starColours = [
'#fffcea', // white
'#fffc4e', // yellowish
'#91f4ff', // blueish
'#ffe1e1', // red ish
'#ffb30a' // orange
]
// lots of parameters
const drawStars = (ctx, cx, cy, radius, qty, size, colours, alpha) => {
const max = randInt(qty[0], qty[1])
for(let i = 0; i < max; i++) {
// draw a bunch of random size random brightness stars around the center
const rx = randInt(cx - radius, cx + radius)
const ry = randInt(cy - radius, cy + radius)
drawCircle(ctx, rx, ry, randInt(size[0], size[1]), pick(colours), randInt(alpha[0], alpha[1]))
}
}
/* -------------------------
* Draw the space background
* 1. Create a bunch of clusters
* 2. Cover the clusters in transparent circles of a given colour (keep the center clear)
* (Alpha of the circles is based on distance from center)
* 3. Draw a bunch of stars on each...