Star Field
It's just like that old screensaver
Source Code for this Sketch
class Star {
static minSize = 3
static maxSize = 6
// speedFactor controls how quickly stars approach
static speedFactor = 1
constructor() {
this.reset()
// More evenly distribute stars in their initial
// starting positions
this.r = pow(random(0, sqrt(this.limit)), 1.8)
}
reset() {
this.r = 0
this.x = 0
this.y = 0
this.speed = sqrt(random(.1, 8)) * Star.speedFactor
this.size = random(Star.minSize, Star.maxSize)
this.deg = random(0, 360)
this.hue = random(0, 360)
this.limit = max(width, height)
}
// multiplier returns a ratio of this.r to this.limit
// with the given minimum value. min should be between
// 0 and 1
multiplier(min) {
if (typeof min !== 'number') {
min = 0
}
return min + (this.r / this.limit * (1 - min))
}
draw() {
// Position from center
this.r += this.speed * this.multiplier(.2)
fill(this.hue, 70, 90)
this.x = cos(this.deg - 90) * this.r * width / this.limit
this.y = sin(this.deg - 90) * this.r * height / this.limit
circle(this.x, this.y, this.size * this.multiplier())
// detect when stars are outside the visible area and
// reset. note: assumes 0,0 coordinates are centered
if (this.x < -(width + this.size) / 2 ||
this.x > (width + this.size) / 2) {
this.reset()
}
if (this.y < -(height + this.size) / 2 ||
this.y > (height + this.size) / 2) {
this.reset()
}
}
}
let stars = []
function setup() {
createCanvas(800, 400, P2D, canvas)
colorMode(HSL)
angleMode(DEGREES)
ellipseMode(CENTER)
noStroke()
for (const x of Array(400).keys()) {
stars.push(new Star())
}
}
function draw() {
translate(width / 2, height / 2)
background(0)
stars.map((star) => { star.draw() })
}
You may use all or part of the p5 code seen on this page for your own creations, without restriction. Attribution is appreciated but not required.
This sketch also includes the following sources: p5common.js . Sources are available under their respective licenses.