|
| 1 | +import { GlowParticle } from "./glowparticle.js"; |
| 2 | + |
| 3 | +const COLORS = [ |
| 4 | + { r: 45, g: 74, b: 227 }, // blue |
| 5 | + { r: 250, g: 255, b: 89 }, // yellow |
| 6 | + { r: 255, g: 104, b: 248 }, // pupple |
| 7 | + { r: 44, g: 209, b: 252 }, // skyblue |
| 8 | + { r: 54, g: 233, b: 84 }, // green |
| 9 | +]; |
| 10 | + |
| 11 | +class App { |
| 12 | + constructor() { |
| 13 | + this.canvas = document.createElement("canvas"); |
| 14 | + document.body.appendChild(this.canvas); |
| 15 | + this.ctx = this.canvas.getContext("2d"); |
| 16 | + |
| 17 | + this.pixelRatio = window.devicePixelRatio > 1 ? 2 : 1; |
| 18 | + |
| 19 | + this.totalParticles = 15; |
| 20 | + this.particles = []; |
| 21 | + this.maxRadius = 900; |
| 22 | + this.minRadius = 400; |
| 23 | + |
| 24 | + window.addEventListener("resize", this.resize.bind(this)); |
| 25 | + this.resize(); |
| 26 | + window.requestAnimationFrame(this.animate.bind(this)); |
| 27 | + } |
| 28 | + |
| 29 | + resize() { |
| 30 | + this.stageWidth = document.body.clientWidth; |
| 31 | + this.stageHeight = document.body.clientHeight; |
| 32 | + |
| 33 | + this.canvas.width = this.stageWidth * this.pixelRatio; |
| 34 | + this.canvas.height = this.stageHeight * this.pixelRatio; |
| 35 | + this.ctx.scale(this.pixelRatio, this.pixelRatio); |
| 36 | + |
| 37 | + this.ctx.globalCompositeOperation = "saturation"; |
| 38 | + |
| 39 | + this.createParticles(); |
| 40 | + } |
| 41 | + |
| 42 | + createParticles() { |
| 43 | + let curColor = 0; |
| 44 | + this.particles = []; |
| 45 | + |
| 46 | + for (let i = 0; i < this.totalParticles; i++) { |
| 47 | + const item = new GlowParticle( |
| 48 | + Math.random() * this.stageWidth, |
| 49 | + Math.random() * this.stageHeight, |
| 50 | + Math.random() * (this.maxRadius - this.minRadius) + this.minRadius, |
| 51 | + COLORS[curColor] |
| 52 | + ); |
| 53 | + |
| 54 | + if (++curColor >= COLORS.length) { |
| 55 | + curColor = 0; |
| 56 | + } |
| 57 | + |
| 58 | + this.particles[i] = item; |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + animate() { |
| 63 | + window.requestAnimationFrame(this.animate.bind(this)); |
| 64 | + |
| 65 | + this.ctx.clearRect(0, 0, this.stageWidth, this.stageHeight); |
| 66 | + |
| 67 | + for (let i = 0; i < this.totalParticles; i++) { |
| 68 | + const item = this.particles[i]; |
| 69 | + item.animate(this.ctx, this.stageWidth, this.stageHeight); |
| 70 | + } |
| 71 | + } |
| 72 | +} |
| 73 | + |
| 74 | +window.onload = () => { |
| 75 | + new App(); |
| 76 | +}; |
0 commit comments