JSFiddle - React, Tailwind, and code Playground
HTML
<body>
<canvas id="canvas"></canvas>
<script src="starcraft.js"></script>
</body>
JavaScript
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
function(callback){
window.setTimeOut(callback,1000/60);
};
})();
var particleCount = 100,
particles = [];
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var wW = window.innerWidth, wH = window.innerHeight;
canvas.width = wW;
canvas.height = wH;
function paintCanvas(){
ctx.fillStyle = "rgba(0,0,0,1)";
ctx.fillRect(0,0,wW,wH);
}
function Particle(){
this.x = Math.random() * wW;
this.y = Math.random() * wH;
var numx = Math.random()*2;
var numy = Math.random()*2;
numx *= Math.floor(Math.random()*2) == 1 ? 1 : -1;
numy *= Math.floor(Math.random()*2) == 1 ? 1 : -1;
this.vx = numx;
this.vy = numy;
this.radius = Math.random() * (Math.random()*5);
this.draw = function(){
ctx.fillStyle = "white";
ctx.beginPath();
ctx.arc(this.x,this.y,this.radius,0,Math.PI*2,false);
ctx.fill();
}
}
for (var i=0; i<particleCount; i++){
particles.push(new Particle());
}
function draw(){
paintCanvas();
for(var i = 0; i < particleCount; i++){
p = particles[i];
p.draw();
}
update();
}
function update(){
for (var i =0; i < particleCount; i++){
p = particles[i];
p.x += p.vx;
p.y += p.vy;
if(p.x + p.radius > wW){
p.x = p.radius;
}
else if(p.x - p.radius < 0){
p.x = wW - p.radius;
}
if(p.y + p.radius > wH){
p.y = p.radius;
}
else if(p.y - p.radius < 0){
p.y = wH - p.radius;
}
}
}
function animloop(){
draw();
requestAnimFrame(animloop);
}
animloop();