JSFiddle - React, Tailwind, and code Playground
HTML
<canvas id="c"></canvas>
SCSS
* {
box-sizing: border-box;
}
html, body {
margin: 0;
padding: 0;
background: #f05151;
}
Babel + JSX
const canvas = document.getElementById('c')
const ctx = canvas.getContext('2d')
let stars, starsCount = 100
const width = window.innerWidth
const height = window.innerHeight
ctx.fillRect(0, 0, width, height)
canvas.width = width
canvas.height = height
function randomInteger(min, max) {
let rand = min + Math.random() * (max + 1 - min);
return Math.floor(rand);
}
function randomColor() {
const colorNum = randomInteger(0, 3)
let color
if(colorNum == 0) color = 'blue'
else if(colorNum == 1) color = '#FF7F66'
else if(colorNum == 2) color = '#7ECEFD'
else if(colorNum == 3) color = '#FFF6E5'
return color
}
function randomSpeed() {
const speedNum = randomInteger(0, 3)
let speed
if(speedNum == 0) speed = .01
else if(speedNum == 1) speed = .02
else if(speedNum == 2) speed = .03
else if(speedNum == 3) speed = .04
return speed
}
function Star(x, y, radius) {
this.x = x
this.y = y
this.radius = radius
this.color = randomColor()
this.speed = 1
this.vel = randomSpeed()
this.draw = () => {
ctx.beginPath()
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false)
ctx.fillStyle = this.color
ctx.fill()
ctx.closePath();
}
this.update = () => {
this.speed += this.vel
this.x -= this.speed
this.y += this.speed / 2
this.draw()
if(this.y > height) {
}
}
}
function init() {
stars = []
setInterval(() => {
stars.push(new Star(randomInteger(width / 2, width), randomInteger(0, height), 10))
}, 100)
}
function anim() {
requestAnimationFrame(anim)
ctx.fillStyle = 'hsla(0, 0%, 0%, 0.1';
ctx.fillRect( 0, 0, width, height );
stars.forEach(star => {
star.update()
})
}
init()
anim()