1+ const canvas = document . getElementById ( 'particleCanvas' ) ;
2+ const ctx = canvas . getContext ( '2d' ) ;
3+
4+ // Initial canvas size
5+ canvas . width = window . innerWidth ;
6+ canvas . height = window . innerHeight ;
7+
8+ let particles = [ ] ;
9+ let particleCount = calculateParticleCount ( ) ;
10+
11+ class Particle {
12+ constructor ( ) {
13+ this . reset ( ) ;
14+ this . y = Math . randm ( ) * canvas . height ;
15+ this . fadeDelay = Math . random ( ) * 600 + 100 ;
16+ this . fadeStart = Date . now ( ) + this . fadeDelay ;
17+ this . fadingOut = false ;
18+ }
19+
20+ reset ( ) {
21+ this . x = Math . random ( ) * canvas . width ;
22+ this . y = Math . random ( ) * canvas . height ;
23+ this . speed = Math . random ( ) / 5 + 0.1 ;
24+ this . opacity = 1 ;
25+ this . fadeDelay = Math . random ( ) * 600 + 100 ;
26+ this . fadeStart = Date . now ( ) + this . fadeDelay ;
27+ this . fadingOut = false ;
28+ }
29+
30+ update ( ) {
31+ this . y -= this . speed ;
32+ if ( this . y < 0 ) {
33+ this . reset ( ) ;
34+ }
35+
36+ if ( ! this . fadingOut && Date . now ( ) > this . fadeStart ) {
37+ this . fadingOut = true ;
38+ }
39+
40+ if ( this . fadingOut ) {
41+ this . opacity -= 0.008 ;
42+ if ( this . opacity <= 0 ) {
43+ this . reset ( ) ;
44+ }
45+ }
46+ }
47+
48+ draw ( ) {
49+ ctx . fillStyle = `rgba(${ 255 - ( Math . random ( ) * 255 / 2 ) } , 255, 255, ${ this . opacity } )` ;
50+ ctx . fillRect ( this . x , this . y , 0.4 , Math . random ( ) * 2 + 1 ) ;
51+ }
52+ }
53+
54+ function initParticles ( ) {
55+ particles = [ ] ;
56+ for ( let i = 0 ; i < particleCount ; i ++ ) {
57+ particles . push ( new Particle ( ) ) ;
58+ }
59+ }
60+
61+ function animate ( ) {
62+ ctx . clearRect ( 0 , 0 , canvas . width , canvas . height ) ;
63+ particles . forEach ( particle => {
64+ particle . update ( ) ;
65+ particle . draw ( ) ;
66+ } ) ;
67+ requestAnimationFrame ( animate ) ;
68+ }
69+
70+ function calculateParticleCount ( ) {
71+ return Math . floor ( ( canvas . width * canvas . height ) / 6000 ) ;
72+ }
73+
74+ function onResize ( ) {
75+ canvas . width = window . innerWidth ;
76+ canvas . height = window . innerHeight ;
77+ particleCount = calculateParticleCount ( ) ;
78+ initParticles ( ) ;
79+ }
80+
81+ window . addEventListener ( 'resize' , onResize ) ;
82+
83+ initParticles ( ) ;
84+ animate ( ) ;
0 commit comments