JSFiddle - React, Tailwind, and code Playground
by Kai
JavaScript
var canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d'),
WIDTH = canvas.width = window.innerWidth,
HEIGHT = canvas.height = window.innerHeight;
document.body.appendChild(canvas);
var particles = [],
MAX_PARTICLES = 200;
function Particle (ctx) {
this.ctx = ctx;
this.x = 100;
this.y = 100;
this.xspeed = 50;
this.yspeed = 3.3;
this.size = 2;
this.color = '#000000';
this.wallCollision = true;
}
Particle.prototype.draw = function () {
this.ctx.save();
this.ctx.beginPath();
this.ctx.fillStyle = this.color;
this.ctx.arc(this.x, this.y, this.size, 0, Math.PI*2, true);
this.ctx.fill();
this.ctx.restore();
};
Particle.prototype.update = function () {
this.x = this.x + this.xspeed;
this.y = this.y + this.yspeed;
if (this.wallCollision) {
if (this.x >= WIDTH || this.x <= 0) {
this.xspeed = this.xspeed * -1;
}
if (this.y >= HEIGHT || this.y <= 0) {
this.yspeed = this.yspeed * -1;
}
}
this.draw();
};
var particle = new Particle(ctx);
particles.push(particle);
function loop () {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
for (var i = 0; i < particles.length; i++) {
particles[i].update();
}
}
setInterval(loop, 1000 / 30);