Particles BG
Particles BG
getElementById("canvas1");
const canvasContext = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
window.addEventListener("resize", () => {
canvas.width = document.body.clientWidth;
canvas.height = window.innerHeight
})
var mouse = {
x: null,
y: null,
radius: (canvas.height / 160) * (canvas.width / 160)
};
window.addEventListener("mousemove",
function(event) {
mouse.x = event.x;
mouse.y = event.y;
}
);
class Particle{
constructor(x,y, directionX, directionY, size, colour ) {
this.x = x;
this.y = y;
this.directionX = directionX;
this.directionY = directionY;
this.size = size;
this.color = colour
}
draw() {
canvasContext.beginPath();
canvasContext.arc(this.x, this.y, this.size, 0 , Math.PI * 2, false);
canvasContext.fillStyle = this.color;
canvasContext.fill();
}
update(){
if (this.x > canvas.width || this.x < 0){
this.directionX = -this.directionX;
}
this.x += this.directionX;
this.y += this.directionY;
this.draw();
}
}
function init(){
particleArray = [];
var numberOfParticles = (canvas.height * canvas.width) / 9000
for (let i = 0; i < numberOfParticles; i++) {
var size = (Math.random() * 5) + 1
let x = (Math.random() * ((window.innerWidth - size * 2) - (size * 2)) +
size * 2);
let y = (Math.random() * ((window.innerHeight - size * 2 - size * 2) -
(size * 2)) + size * 2);
let directionX = (Math.random() * 5) - 2.5;
let directionY = (Math.random() * 5) - 2.5;
let color = "#000000";
particleArray.push(new Particle(x,y,directionX,directionY,size,color));
}
}
function connect(){
let opacityValue = 1;
for (let i = 0; i < particleArray.length; i++) {
for (let j = i; j < particleArray.length; j++) {
let dx = (particleArray[i].x - particleArray[j].x);
let dy = (particleArray[i].y - particleArray[j].y);
let distance = (dx*dx) + (dy*dy);
if (distance < Math.pow((canvas.width/10),2)){
opacityValue = 1 - (distance/20000);
canvasContext.strokeStyle = `rgba(0,0,0,${opacityValue})`;
canvasContext.lineWidth = 1;
canvasContext.beginPath();
canvasContext.moveTo(particleArray[i].x, particleArray[i].y);
canvasContext.lineTo(particleArray[j].x, particleArray[j].y)
canvasContext.stroke();
}
}
}
}
function animate(){
requestAnimationFrame(animate)
canvasContext.clearRect(0,0,canvas.width,canvas.height);
init();
animate();