portfolio/themes/warwick_portfolio/assets/js/background.js

100 lines
2.4 KiB
JavaScript
Executable file

// create background element
let canvas = document.createElement("canvas");
document.body.appendChild(canvas);
canvas.style.cssText = `
background: #00000000;
position:fixed;
left:0;
top:0;
z-index:-99999;
`
// set it's size
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
let context = canvas.getContext('2d');
// this will be populated and used later
drawableObjectList = [];
class Splash {
constructor(distance, x, y) {
this.distance = distance;
this.x = x;
this.y = y;
this.time = 0;
}
draw() {
context.fillStyle = "#00000000";
context.strokeStyle = `rgba(140, 36, 13, ${this.distance + 0.1})`;
let splashSize = this.distance * (this.time/100);
context.beginPath();
context.ellipse(this.x, this.y, 100 * splashSize , 50 * splashSize, 0, 0, Math.PI * 2);
context.fill();
context.stroke();
if (this.time > 100) {
drawableObjectList = drawableObjectList.filter((item) => {return item !== this});
}
this.time += 1;
}
}
// this is the object that'll look cool
class Drop {
constructor() {
this.x = Math.random() * window.innerWidth;
this.y = Math.random() * window.innerHeight;
this.distance = Math.random();
}
draw() {
context.fillStyle = `rgba(140, 36, 13, ${this.distance + 0.1})`;
context.strokeStyle = `rgba(140, 36, 13, ${this.distance + 0.1})`;
// draw point
context.beginPath();
context.moveTo(this.x,this.y);
context.lineTo(this.x,this.y-this.distance*100);
context.stroke();
// move point
this.y += (this.distance + 0.3) * 4;
// keep point in bounds
if (this.y > window.innerHeight - (1 - this.distance) * 300) {
// Add splash
drawableObjectList.push(new Splash(this.distance, this.x, this.y))
this.y = 0
this.x = Math.random() * window.innerWidth;
this.distance = Math.random();
}
}
}
// populate element array
for (let i = 0; i < 50; i++) {
drawableObjectList.push(new Drop());
}
function loop() {
// Loop and clear frame
requestAnimationFrame(loop);
context.clearRect(0, 0, window.innerWidth, window.innerHeight);
// Draw objects.
drawableObjectList.forEach((point) => {
point.draw();
});
// Handle page size change
if (canvas.width != window.innerWidth) {
canvas.width = window.innerWidth;
}
if (canvas.height != window.innerHeight) {
canvas.height = window.innerHeight;
}
}
loop();