beautiful-backgrounds 0.0.1 → 0.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,115 @@
1
+ # Beautiful Backgrounds
2
+
3
+ [![Build][build-badge]][build]
4
+
5
+ The "Beautiful Backgrounds" library offers a collection of customizable web components designed to enhance web pages with visually appealing animated backgrounds. Easy to integrate and use, these components are perfect for adding dynamic and interactive elements to your web applications.
6
+
7
+ [EXAMPLES][examples]
8
+
9
+ ## Features
10
+
11
+ - **Multiple Background Components**: A variety of background components, each offering unique visual effects.
12
+ - **Customizable and Interactive**: Each component comes with customizable properties to suit different design needs.
13
+ - **Responsive and Efficient**: Components are responsive to screen size changes and optimized for performance.
14
+
15
+ ## Installation
16
+
17
+ Using [`npm`][npm]:
18
+
19
+ ```sh
20
+ npm i beautiful-backgrounds --save
21
+ ```
22
+
23
+ ```js
24
+ import { BbStarTrail } from 'beautiful-backgrounds';
25
+ ```
26
+
27
+ In browsers with [`esm.sh`][esmsh]:
28
+
29
+ ```html
30
+ <script type="module">
31
+ import { BbStarTrail } from 'https://esm.sh/beautiful-backgrounds';
32
+ </script>
33
+ ```
34
+
35
+ ## Usage
36
+
37
+ ### Star Trail
38
+
39
+ ```html
40
+ <bb-star-trail
41
+ data-num-stars="567"
42
+ data-star-size-min="0.1"
43
+ data-star-size-max="1.5"
44
+ data-star-speed-min="0.001"
45
+ data-star-speed-max="0.003"
46
+ data-star-color-hue-start="30"
47
+ data-star-color-hue-end="75"
48
+ data-orbit-radius-min="10"
49
+ data-orbit-radius-max="300"
50
+ data-star-lifespan-min="1000"
51
+ data-star-lifespan-max="50000"
52
+ data-width="500"
53
+ data-height="500"
54
+ ></bb-star-trail>
55
+ ```
56
+
57
+ #### Attributes for bb-star-trail
58
+
59
+ - `data-num-stars`: Number of stars to be rendered.
60
+ - `data-star-size-min`: Minimum size of a star.
61
+ - `data-star-size-max`: Maximum size of a star.
62
+ - `data-star-speed-min`: Minimum speed of a star.
63
+ - `data-star-speed-max`: Maximum speed of a star.
64
+ - `data-star-color-hue-start`: Starting hue for star color. Should be a value between 0 and 360.
65
+ - `data-star-color-hue-end`: Ending hue for star color. Should be a value between 0 and 360.
66
+ - `data-star-color-saturation-start`: Specifies the starting color saturation for star color. Should be a value between 0 and 100.
67
+ - `data-star-color-saturation-start`: Specifies the ending color saturation for star color. Should be a value between 0 and 100.
68
+ - `data-star-color-lightness-start`: Specifies the starting color lightness for star color. Should be a value between 0 and 100.
69
+ - `data-star-color-lightness-start`: Specifies the ending color lightness for star color. Should be a value between 0 and 100.
70
+ - `data-radius-min`: Minimum radius for star orbit.
71
+ - `data-radius-max`: Maximum radius for star orbit.
72
+ - `data-star-lifespan-min`: Minimum lifespan of a star in milliseconds.
73
+ - `data-star-lifespan-max`: Maximum lifespan of a star in milliseconds.
74
+ - `data-width`: Width of the star trail component, remove to fit the size of the container
75
+ - `data-height`: height of the star trail component, remove to fit the size of the container
76
+ - `data-background-color`: Background color of the canvas element
77
+
78
+ ### Digital Rain
79
+
80
+ ```html
81
+ <bb-digital-rain
82
+ data-characteras="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
83
+ data-font-size="16"
84
+ data-font-color-hue-start="#0F0"
85
+ data-font-color-hue-end="#0F0"
86
+ data-speed="1"
87
+ ></bb-star-trail>
88
+ ```
89
+
90
+ #### Attributes for bb-digital-rain
91
+
92
+ - `data-characters`: Sets the characters for the digital rain effect.
93
+ - `data-font-size`: Defines the font size of the falling characters.
94
+ - `data-font-color-hue-start`: Specifies the starting color hue for the rain. Should be a value between 0 and 360.
95
+ - `data-font-color-hue-end`: Sets the ending color hue for the rain. Should be a value between 0 and 360.
96
+ - `data-font-color-saturation-start`: Specifies the starting color saturation for the rain. Should be a value between 0 and 100.
97
+ - `data-font-color-saturation-start`: Specifies the ending color saturation for the rain. Should be a value between 0 and 100.
98
+ - `data-font-color-lightness-start`: Specifies the starting color lightness for the rain. Should be a value between 0 and 100.
99
+ - `data-font-color-lightness-start`: Specifies the ending color lightness for the rain. Should be a value between 0 and 100.
100
+ - `data-speed`: Controls the falling speed of the digital rain.
101
+ - `data-background-color`: Background color of the canvas element
102
+
103
+ [![ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/A0A3QJPZ9)
104
+
105
+ <!-- Links -->
106
+
107
+ [build-badge]: https://github.com/niekes/beautiful-backgrounds/workflows/main/badge.svg
108
+
109
+ [build]: https://github.com/niekes/beautiful-backgrounds/actions
110
+
111
+ [esmsh]: https://esm.sh
112
+
113
+ [npm]: https://www.npmjs.com/package/beautiful-backgrounds
114
+
115
+ [examples]: https://codepen.io/collection/aMPozo
@@ -0,0 +1 @@
1
+ !function(t,i){"object"==typeof exports&&"undefined"!=typeof module?i(exports):"function"==typeof define&&define.amd?define(["exports"],i):i((t="undefined"!=typeof globalThis?globalThis:t||self).version={})}(this,(function(t){"use strict";class i extends HTMLElement{constructor(){super(),this.interpolationDuration=1e3,this.interpolationStep=100,this.fullyInitialized=!1,this.shadowR=this.attachShadow({mode:"open"}),this.shadowR.innerHTML="\n <style>\n :host {\n display: flex;\n }\n </style>\n ",this.resizeDebounceTimer=null,this.canvas=document.createElement("canvas"),this.ctx=this.canvas.getContext("2d")}debouncedResizeCanvas(){clearTimeout(this.resizeDebounceTimer),this.resizeDebounceTimer=setTimeout((()=>{this.resizeCanvas()}),1e3)}interpolateWithThrottle(t,i,s,a,e){const h=Math.ceil(s/a),n=(i-t)/h;let r=t,o=0,l=!0,d=null;!function t(){o<s&&l?(e(r,!1),r+=n,o+=a,d=window.setTimeout(t,a)):l&&(e(i,!0),l=!1,d&&window.clearTimeout(d))}()}triggerInterpolation(t,i,s){const a=Number(i),e=Number(s),h=this.getPropNameCamelCased(t);var n,r;a!==e&&this.fullyInitialized?(n=this,r=h,Object.prototype.hasOwnProperty.call(n,r)&&this.interpolateWithThrottle(i?a:this[h],e,this.interpolationDuration,this.interpolationStep,(t=>{this[h]=t}))):this[h]=e}setValues(t,i,s,a){if(t.includes(i)){this[this.getPropNameCamelCased(i)]=a}t.includes(i)||this.triggerInterpolation(i,s,a)}getPropNameCamelCased(t){return t.substring(5).replace(/-(.)/g,((t,i)=>i.toUpperCase()))}resizeCanvas(){const t=Number.parseInt(this.getAttribute("data-width"))||this.parentElement.clientWidth,i=Number.parseInt(this.getAttribute("data-height"))||this.parentElement.clientHeight;t===this.width&&i===this.height||(this.width=t,this.height=i,this.canvas.width=t,this.canvas.height=i),this.fullyInitialized=!0}}function s(t,i){return Math.random()*(i-t)+t}function a(t,i){return t=Math.ceil(t),i=Math.floor(i),Math.floor(Math.random()*(i-t+1)+t)}function e(t,i,s,a,e){t<i&&(t=i),t>s&&(t=s);return(t-i)/(s-i)*(e-a)+a}class h{constructor(t,i,e,h,n,r){this.amplitudeX=a(-350,350),this.amplitudeY=a(-350,350),this.frequencyX=s(-1,1),this.frequencyY=s(-1,1),this.time=0,this.dampingFactor=.1,this.phaseX=a(10,70),this.phaseY=a(10,400),this.heartScale=a(10,20),this.deltaRadius=1,this.dx=1,this.size=t,this.speed=i,this.color=e,this.radius=h,this.angle=n,this.lifespan=r,this.x=0,this.y=0,this.born=Date.now(),this.fadeInDuration=.25*this.lifespan,this.fadeOutDuration=.5*this.lifespan}heartShapeMotion(t,i){this.x=t+this.heartScale*(16*Math.pow(Math.sin(this.angle),3)),this.y=i-this.heartScale*(13*Math.cos(this.angle)-5*Math.cos(2*this.angle)-2*Math.cos(3*this.angle)-Math.cos(4*this.angle)),this.angle-=this.speed}spiralMotion(t,i){this.radius+=this.deltaRadius,this.x=t+this.radius*Math.cos(this.angle),this.y=i+this.radius*Math.sin(this.angle),this.angle+=this.speed}updatse(t,i){this.x+=this.dx,this.y=this.amplitudeX*Math.sin(this.frequencyX*this.x+this.phaseX)}dampedHarmonicMotion(t,i){let s=this.amplitudeX*Math.pow(this.dampingFactor,this.time),a=this.amplitudeY*Math.pow(this.dampingFactor,this.time);this.x=t+s*Math.sin(this.frequencyX*this.time+this.phaseX),this.y=i+a*Math.sin(this.frequencyY*this.time+this.phaseY),this.time+=this.speed}update(t,i){this.angle+=this.speed,this.x=t+Math.cos(this.angle)*this.radius,this.y=i+Math.sin(this.angle)*this.radius}ellipticalMotion(t,i){this.angle+=this.speed,this.x=t+this.radius*Math.cos(this.angle),this.y=i+this.radius*Math.sin(this.angle)}draw(t){const i=this.calculateOpacity();t.beginPath(),t.arc(this.x,this.y,this.size,0,2*Math.PI,!1),t.fillStyle=this.color,t.globalAlpha=i,t.shadowBlur=10,t.shadowColor=this.color,t.fill(),t.globalAlpha=1,t.shadowBlur=0}isDead(){return Date.now()-this.born>this.lifespan}calculateOpacity(){const t=Date.now()-this.born;return t<this.fadeInDuration?t/this.fadeInDuration:t>this.lifespan-this.fadeOutDuration?(this.lifespan-t)/this.fadeOutDuration:1}}function n(t=[0,360],i=[0,100],s=[40,60]){return`hsl(${a(t[0],t[1])}, ${a(i[0],i[1])}%, ${a(s[0],s[1])}%)`}class r extends i{constructor(){super(),this.ignoredProps=["data-characters","data-background-color"],this.backgroundColor="0, 0, 0",this.starSizeMin=.5,this.starSizeMax=1.5,this.starSpeedMin=.025,this.starSpeedMax=.05,this.starColorHueStart=30,this.starColorHueEnd=75,this.starColorSaturationStart=100,this.starColorSaturationEnd=100,this.starColorLightnessStart=50,this.starColorLightnessEnd=50,this.starRadiusMin=1,this.starRadiusMax=100,this.starLifespanMin=1e3,this.starLifespanMax=1e4,this.numStars=1e3,this.trailOpacity=.1}connectedCallback(){this.shadowR.appendChild(this.canvas),this.resizeCanvas(),this.initialize(),this.startAnimation(),window.addEventListener("resize",this.debouncedResizeCanvas.bind(this))}disconnectedCallback(){window.removeEventListener("resize",this.debouncedResizeCanvas.bind(this)),null!==this.animationFrameId&&window.cancelAnimationFrame(this.animationFrameId)}initialize(){this.stars=[],this.starRadiusMax=Math.max(this.width,this.height)/2,this.animationFrameId=null;for(let t=0;t<this.numStars;t++)this.stars.push(this.createStar())}startAnimation(){const t=()=>{for(this.ctx.fillStyle=`rgba(${this.backgroundColor}, ${this.trailOpacity})`,this.ctx.fillRect(0,0,this.width,this.height),this.stars=this.stars.filter((t=>!t.isDead()));this.stars.length<this.numStars;)this.stars.push(this.createStar());this.stars.forEach((t=>{t.update(this.width/2,this.height/2),t.draw(this.ctx)})),this.animationFrameId=requestAnimationFrame(t)};this.animationFrameId=requestAnimationFrame(t)}createStar(){const t=s(this.starSizeMin,this.starSizeMax),i=s(e(this.starSpeedMin,-1,1,-.04,.04),e(this.starSpeedMax,-1,1,-.04,.04)),a=s(this.starLifespanMin,this.starLifespanMax),r=n([this.starColorHueStart,this.starColorHueEnd],[this.starColorSaturationStart,this.starColorSaturationEnd],[this.starColorLightnessStart,this.starColorLightnessEnd]),o=s(0,2*Math.PI),l=this.starRadiusMax-this.starRadiusMin,d=Math.sqrt(Math.random())*l+this.starRadiusMin;return new h(t,i,r,d,o,a)}attributeChangedCallback(t,i,s){this.setValues(this.ignoredProps,t,i,s)}}r.observedAttributes=["data-background-color","data-star-size-min","data-star-size-max","data-star-speed-min","data-star-speed-max","data-star-color-hue-start","data-star-color-hue-end","data-star-color-saturation-start","data-star-color-saturation-end","data-star-color-lightness-start","data-star-color-lightness-end","data-star-radius-min","data-star-radius-max","data-star-lifespan-min","data-star-lifespan-max","data-num-stars"],window.customElements.get("bb-star-trail")||window.customElements.define("bb-star-trail",r);class o extends i{constructor(){super(),this.ignoredProps=["data-characters","data-background-color"],this.backgroundColor="0, 0, 0",this.fontSize=24,this.fontColorHueStart=60,this.fontColorHueEnd=150,this.fontColorSaturationStart=90,this.fontColorSaturationEnd=100,this.fontColorLightnessStart=50,this.fontColorLightnessEnd=50,this.speed=2,this.randomness=.9,this.trailOpacity=.1,this.characters='ヲアウエオカキケコサシスセソタツテナニヌネハヒホマミムメモヤユラリワ13579ヲイクコソチΦトノフヤヨルレロンZ:・."¦=*+-<>|リçδ╘'}connectedCallback(){this.shadowR.appendChild(this.canvas),this.resizeCanvas(),this.initialize(),this.startAnimation(),window.addEventListener("resize",this.debouncedResizeCanvas.bind(this))}disconnectedCallback(){window.removeEventListener("resize",this.debouncedResizeCanvas.bind(this)),null!==this.animationFrameId&&window.cancelAnimationFrame(this.animationFrameId)}initialize(){this.columns=Math.floor(this.width/this.fontSize),this.rain=Array(this.columns).fill(this.height)}startAnimation(){const t=()=>{this.ctx.fillStyle=`rgba(${this.backgroundColor}, ${this.trailOpacity})`,this.ctx.fillRect(0,0,this.width,this.height),this.ctx.font=`${this.fontSize}px monospace`;for(let t=0;t<this.rain.length;t++){if(this.rain[t]%this.speed==0){const i=this.characters.charAt(Math.floor(Math.random()*this.characters.length));this.ctx.fillStyle=n([this.fontColorHueStart,this.fontColorHueEnd],[this.fontColorSaturationStart,this.fontColorSaturationEnd],[this.fontColorLightnessStart,this.fontColorLightnessEnd]),this.ctx.fillText(i,t*this.fontSize,this.rain[t]/this.speed*this.fontSize),this.rain[t]/this.speed*this.fontSize>this.height&&Math.random()>this.randomness&&(this.rain[t]=0)}this.rain[t]++}this.animationFrameId=requestAnimationFrame(t)};this.animationFrameId=requestAnimationFrame(t)}attributeChangedCallback(t,i,s){this.setValues(this.ignoredProps,t,i,s)}}o.observedAttributes=["data-characters","data-speed","data-randomness","data-font-size","data-font-color-hue-start","data-font-color-hue-end","data-font-color-saturation-start","data-font-color-saturation-end","data-font-color-lightness-start","data-font-color-lightness-end","data-background-color"],window.customElements.get("bb-digital-rain")||window.customElements.define("bb-digital-rain",o),t.BbDigitalRain=o,t.BbStarTrail=r}));
@@ -5,13 +5,17 @@ export default abstract class BeautifulBackground extends HTMLElement {
5
5
  protected canvas: HTMLCanvasElement;
6
6
  protected ctx: CanvasRenderingContext2D;
7
7
  private resizeDebounceTimer;
8
+ private interpolationDuration;
9
+ private interpolationStep;
10
+ private fullyInitialized;
8
11
  constructor();
9
12
  protected abstract connectedCallback(): void;
10
13
  protected abstract disconnectedCallback(): void;
11
14
  protected abstract initialize(): void;
12
15
  protected debouncedResizeCanvas(): void;
16
+ protected interpolateWithThrottle(startValue: number, newValue: number, durationMs: number, throttleMs: number, onInterpolate: Function): void;
17
+ protected triggerInterpolation(name: string, oldValue: string, newValue: string): void;
18
+ protected setValues(ignoredProps: string[], name: string, oldValue: string, newValue: string): void;
19
+ protected getPropNameCamelCased(dashCased: string): string;
13
20
  protected resizeCanvas(): void;
14
- protected setSize(): void;
15
- protected parseAttributeToFloat(attr: string, prefix?: string): number;
16
- protected parseAttributeToInt(attr: string, prefix?: string): number;
17
21
  }
@@ -1,6 +1,10 @@
1
+ import { has } from '../utils/object';
1
2
  export default class BeautifulBackground extends HTMLElement {
2
3
  constructor() {
3
4
  super();
5
+ this.interpolationDuration = 1000;
6
+ this.interpolationStep = 100;
7
+ this.fullyInitialized = false;
4
8
  this.shadowR = this.attachShadow({ mode: 'open' });
5
9
  this.shadowR.innerHTML = `
6
10
  <style>
@@ -19,22 +23,68 @@ export default class BeautifulBackground extends HTMLElement {
19
23
  this.resizeCanvas();
20
24
  }, 1000); // Adjust the debounce time as needed
21
25
  }
22
- resizeCanvas() {
23
- this.setSize();
24
- this.initialize();
26
+ interpolateWithThrottle(startValue, newValue, durationMs, throttleMs, onInterpolate) {
27
+ const numSteps = Math.ceil(durationMs / throttleMs);
28
+ const stepValue = (newValue - startValue) / numSteps;
29
+ let currentValue = startValue;
30
+ let currentTime = 0;
31
+ let isInterpolating = true;
32
+ let timeoutID = null;
33
+ function interpolateStep() {
34
+ if (currentTime < durationMs && isInterpolating) {
35
+ onInterpolate(currentValue, false);
36
+ currentValue += stepValue;
37
+ currentTime += throttleMs;
38
+ timeoutID = window.setTimeout(interpolateStep, throttleMs);
39
+ }
40
+ else if (isInterpolating) {
41
+ onInterpolate(newValue, true);
42
+ isInterpolating = false;
43
+ if (timeoutID) {
44
+ window.clearTimeout(timeoutID);
45
+ }
46
+ }
47
+ }
48
+ interpolateStep();
25
49
  }
26
- setSize() {
27
- this.width =
28
- Number.parseInt(this.getAttribute('data-width')) || this.parentElement.clientWidth;
29
- this.height =
30
- Number.parseInt(this.getAttribute('data-height')) || this.parentElement.clientHeight;
31
- this.canvas.width = this.width;
32
- this.canvas.height = this.height;
50
+ triggerInterpolation(name, oldValue, newValue) {
51
+ const old = Number(oldValue);
52
+ const target = Number(newValue);
53
+ const prop = this.getPropNameCamelCased(name);
54
+ if (old !== target && this.fullyInitialized) {
55
+ if (has(this, prop)) {
56
+ this.interpolateWithThrottle(oldValue ? old : this[prop], target, this.interpolationDuration, this.interpolationStep, (i) => {
57
+ this[prop] = i;
58
+ });
59
+ }
60
+ }
61
+ else {
62
+ this[prop] = target;
63
+ }
33
64
  }
34
- parseAttributeToFloat(attr, prefix = 'data') {
35
- return Number.parseFloat(this.getAttribute(`${prefix}-${attr}`));
65
+ setValues(ignoredProps, name, oldValue, newValue) {
66
+ if (ignoredProps.includes(name)) {
67
+ const propName = this.getPropNameCamelCased(name);
68
+ this[propName] = newValue;
69
+ }
70
+ if (!ignoredProps.includes(name)) {
71
+ this.triggerInterpolation(name, oldValue, newValue);
72
+ }
36
73
  }
37
- parseAttributeToInt(attr, prefix = 'data') {
38
- return Number.parseInt(this.getAttribute(`${prefix}-${attr}`));
74
+ getPropNameCamelCased(dashCased) {
75
+ return dashCased
76
+ .substring(5)
77
+ .replace(/-(.)/g, (_, char) => char.toUpperCase());
78
+ }
79
+ resizeCanvas() {
80
+ const newWidth = Number.parseInt(this.getAttribute('data-width')) || this.parentElement.clientWidth;
81
+ const newHeight = Number.parseInt(this.getAttribute('data-height')) || this.parentElement.clientHeight;
82
+ if (newWidth !== this.width || newHeight !== this.height) {
83
+ this.width = newWidth;
84
+ this.height = newHeight;
85
+ this.canvas.width = newWidth;
86
+ this.canvas.height = newHeight;
87
+ }
88
+ this.fullyInitialized = true;
39
89
  }
40
90
  }
@@ -0,0 +1,26 @@
1
+ import BB from './BeautifulBackground';
2
+ export declare class BbDigitalRain extends BB {
3
+ backgroundColor: string;
4
+ fontSize: number;
5
+ fontColorHueStart: number;
6
+ fontColorHueEnd: number;
7
+ fontColorSaturationStart: number;
8
+ fontColorSaturationEnd: number;
9
+ fontColorLightnessStart: number;
10
+ fontColorLightnessEnd: number;
11
+ columns: number;
12
+ speed: number;
13
+ randomness: number;
14
+ characters: string;
15
+ rain: number[];
16
+ private trailOpacity;
17
+ private animationFrameId;
18
+ static observedAttributes: string[];
19
+ protected ignoredProps: string[];
20
+ constructor();
21
+ protected connectedCallback(): void;
22
+ protected disconnectedCallback(): void;
23
+ protected initialize(): void;
24
+ protected startAnimation(): void;
25
+ attributeChangedCallback(name: string, oldValue: string, newValue: string): void;
26
+ }
@@ -0,0 +1,78 @@
1
+ import BB from './BeautifulBackground';
2
+ import { randomColor } from '../utils/color';
3
+ export class BbDigitalRain extends BB {
4
+ constructor() {
5
+ super();
6
+ this.ignoredProps = ['data-characters', 'data-background-color'];
7
+ this.backgroundColor = '0, 0, 0';
8
+ this.fontSize = 24;
9
+ this.fontColorHueStart = 60;
10
+ this.fontColorHueEnd = 150;
11
+ this.fontColorSaturationStart = 90;
12
+ this.fontColorSaturationEnd = 100;
13
+ this.fontColorLightnessStart = 50;
14
+ this.fontColorLightnessEnd = 50;
15
+ this.speed = 2;
16
+ this.randomness = 0.9;
17
+ this.trailOpacity = 0.1;
18
+ this.characters =
19
+ 'ヲアウエオカキケコサシスセソタツテナニヌネハヒホマミムメモヤユラリワ13579ヲイクコソチΦトノフヤヨルレロンZ:・."¦=*+-<>|リçδ╘';
20
+ }
21
+ connectedCallback() {
22
+ this.shadowR.appendChild(this.canvas);
23
+ this.resizeCanvas();
24
+ this.initialize();
25
+ this.startAnimation();
26
+ window.addEventListener('resize', this.debouncedResizeCanvas.bind(this));
27
+ }
28
+ disconnectedCallback() {
29
+ window.removeEventListener('resize', this.debouncedResizeCanvas.bind(this));
30
+ if (this.animationFrameId !== null) {
31
+ window.cancelAnimationFrame(this.animationFrameId);
32
+ }
33
+ }
34
+ initialize() {
35
+ this.columns = Math.floor(this.width / this.fontSize);
36
+ this.rain = Array(this.columns).fill(this.height);
37
+ }
38
+ startAnimation() {
39
+ const animate = () => {
40
+ this.ctx.fillStyle = `rgba(${this.backgroundColor}, ${this.trailOpacity})`;
41
+ this.ctx.fillRect(0, 0, this.width, this.height);
42
+ this.ctx.font = `${this.fontSize}px monospace`;
43
+ for (let i = 0; i < this.rain.length; i++) {
44
+ if (this.rain[i] % this.speed === 0) {
45
+ const text = this.characters.charAt(Math.floor(Math.random() * this.characters.length));
46
+ this.ctx.fillStyle = randomColor([this.fontColorHueStart, this.fontColorHueEnd], [this.fontColorSaturationStart, this.fontColorSaturationEnd], [this.fontColorLightnessStart, this.fontColorLightnessEnd]);
47
+ this.ctx.fillText(text, i * this.fontSize, (this.rain[i] / this.speed) * this.fontSize);
48
+ if ((this.rain[i] / this.speed) * this.fontSize > this.height &&
49
+ Math.random() > this.randomness) {
50
+ this.rain[i] = 0;
51
+ }
52
+ }
53
+ this.rain[i]++;
54
+ }
55
+ this.animationFrameId = requestAnimationFrame(animate);
56
+ };
57
+ this.animationFrameId = requestAnimationFrame(animate);
58
+ }
59
+ attributeChangedCallback(name, oldValue, newValue) {
60
+ this.setValues(this.ignoredProps, name, oldValue, newValue);
61
+ }
62
+ }
63
+ BbDigitalRain.observedAttributes = [
64
+ 'data-characters',
65
+ 'data-speed',
66
+ 'data-randomness',
67
+ 'data-font-size',
68
+ 'data-font-color-hue-start',
69
+ 'data-font-color-hue-end',
70
+ 'data-font-color-saturation-start',
71
+ 'data-font-color-saturation-end',
72
+ 'data-font-color-lightness-start',
73
+ 'data-font-color-lightness-end',
74
+ 'data-background-color'
75
+ ];
76
+ if (!window.customElements.get('bb-digital-rain')) {
77
+ window.customElements.define('bb-digital-rain', BbDigitalRain);
78
+ }
@@ -0,0 +1,34 @@
1
+ export default class Particle {
2
+ private size;
3
+ private speed;
4
+ private color;
5
+ private radius;
6
+ private angle;
7
+ private lifespan;
8
+ private x;
9
+ private y;
10
+ private born;
11
+ private fadeInDuration;
12
+ private fadeOutDuration;
13
+ amplitudeX: number;
14
+ amplitudeY: number;
15
+ frequencyX: number;
16
+ frequencyY: number;
17
+ time: number;
18
+ dampingFactor: number;
19
+ phaseX: number;
20
+ phaseY: number;
21
+ heartScale: number;
22
+ deltaRadius: number;
23
+ dx: number;
24
+ constructor(size: number, speed: number, color: string, radius: number, angle: number, lifespan: number);
25
+ heartShapeMotion(centerX: number, centerY: number): void;
26
+ spiralMotion(centerX: number, centerY: number): void;
27
+ updatse(centerX: number, centerY: number): void;
28
+ dampedHarmonicMotion(centerX: number, centerY: number): void;
29
+ update(centerX: number, centerY: number): void;
30
+ ellipticalMotion(centerX: number, centerY: number): void;
31
+ draw(ctx: CanvasRenderingContext2D): void;
32
+ isDead(): boolean;
33
+ private calculateOpacity;
34
+ }
@@ -0,0 +1,98 @@
1
+ import { getRandomInt, getRandomFloat } from '../utils/number';
2
+ export default class Particle {
3
+ constructor(size, speed, color, radius, angle, lifespan) {
4
+ this.amplitudeX = getRandomInt(-350, 350);
5
+ this.amplitudeY = getRandomInt(-350, 350);
6
+ this.frequencyX = getRandomFloat(-1, 1);
7
+ this.frequencyY = getRandomFloat(-1, 1);
8
+ this.time = 0;
9
+ this.dampingFactor = 0.1;
10
+ this.phaseX = getRandomInt(10, 70);
11
+ this.phaseY = getRandomInt(10, 400);
12
+ this.heartScale = getRandomInt(10, 20); // Adjust this to scale the size of the heart
13
+ this.deltaRadius = 1;
14
+ this.dx = 1;
15
+ this.size = size;
16
+ this.speed = speed;
17
+ this.color = color;
18
+ this.radius = radius;
19
+ this.angle = angle;
20
+ this.lifespan = lifespan;
21
+ this.x = 0;
22
+ this.y = 0;
23
+ this.born = Date.now();
24
+ this.fadeInDuration = this.lifespan * 0.25;
25
+ this.fadeOutDuration = this.lifespan * 0.5;
26
+ }
27
+ heartShapeMotion(centerX, centerY) {
28
+ // Parametric equations for the heart shape
29
+ this.x = centerX + this.heartScale * (16 * Math.pow(Math.sin(this.angle), 3));
30
+ this.y =
31
+ centerY -
32
+ this.heartScale *
33
+ (13 * Math.cos(this.angle) -
34
+ 5 * Math.cos(2 * this.angle) -
35
+ 2 * Math.cos(3 * this.angle) -
36
+ Math.cos(4 * this.angle));
37
+ // Increment the angle
38
+ this.angle -= this.speed; // Adjust as needed for speed
39
+ }
40
+ spiralMotion(centerX, centerY) {
41
+ // Gradually increase the radius to continue the spiral motion
42
+ this.radius += this.deltaRadius;
43
+ // Calculate the new position
44
+ this.x = centerX + this.radius * Math.cos(this.angle);
45
+ this.y = centerY + this.radius * Math.sin(this.angle);
46
+ // Increment the angle for the next position
47
+ this.angle += this.speed;
48
+ }
49
+ updatse(centerX, centerY) {
50
+ this.x += this.dx;
51
+ this.y = this.amplitudeX * Math.sin(this.frequencyX * this.x + this.phaseX);
52
+ }
53
+ dampedHarmonicMotion(centerX, centerY) {
54
+ // Applying damping to the amplitude
55
+ let dampedAmplitudeX = this.amplitudeX * Math.pow(this.dampingFactor, this.time);
56
+ let dampedAmplitudeY = this.amplitudeY * Math.pow(this.dampingFactor, this.time);
57
+ // Calculate the new position with the damped amplitude
58
+ this.x = centerX + dampedAmplitudeX * Math.sin(this.frequencyX * this.time + this.phaseX);
59
+ this.y = centerY + dampedAmplitudeY * Math.sin(this.frequencyY * this.time + this.phaseY);
60
+ // Increment the time
61
+ this.time += this.speed; // Increment can be adjusted based on desired speed
62
+ }
63
+ update(centerX, centerY) {
64
+ this.angle += this.speed;
65
+ this.x = centerX + Math.cos(this.angle) * this.radius;
66
+ this.y = centerY + Math.sin(this.angle) * this.radius;
67
+ }
68
+ ellipticalMotion(centerX, centerY) {
69
+ this.angle += this.speed;
70
+ this.x = centerX + this.radius * Math.cos(this.angle);
71
+ this.y = centerY + this.radius * Math.sin(this.angle);
72
+ }
73
+ draw(ctx) {
74
+ const opacity = this.calculateOpacity();
75
+ ctx.beginPath();
76
+ ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2, false);
77
+ ctx.fillStyle = this.color;
78
+ ctx.globalAlpha = opacity;
79
+ ctx.shadowBlur = 10;
80
+ ctx.shadowColor = this.color;
81
+ ctx.fill();
82
+ ctx.globalAlpha = 1;
83
+ ctx.shadowBlur = 0;
84
+ }
85
+ isDead() {
86
+ return Date.now() - this.born > this.lifespan;
87
+ }
88
+ calculateOpacity() {
89
+ const age = Date.now() - this.born;
90
+ if (age < this.fadeInDuration) {
91
+ return age / this.fadeInDuration; // Fade in
92
+ }
93
+ else if (age > this.lifespan - this.fadeOutDuration) {
94
+ return (this.lifespan - age) / this.fadeOutDuration; // Fade out
95
+ }
96
+ return 1; // Fully visible
97
+ }
98
+ }
@@ -0,0 +1,32 @@
1
+ import BB from './BeautifulBackground';
2
+ import Particle from './Particle';
3
+ export declare class BbStarTrail extends BB {
4
+ backgroundColor: string;
5
+ starSizeMin: number;
6
+ starSizeMax: number;
7
+ starSpeedMin: number;
8
+ starSpeedMax: number;
9
+ starColorHueStart: number;
10
+ starColorHueEnd: number;
11
+ starColorSaturationStart: number;
12
+ starColorSaturationEnd: number;
13
+ starColorLightnessStart: number;
14
+ starColorLightnessEnd: number;
15
+ starRadiusMin: number;
16
+ starRadiusMax: number;
17
+ starLifespanMin: number;
18
+ starLifespanMax: number;
19
+ numStars: number;
20
+ private trailOpacity;
21
+ private stars;
22
+ private animationFrameId;
23
+ static observedAttributes: string[];
24
+ private ignoredProps;
25
+ constructor();
26
+ protected connectedCallback(): void;
27
+ protected disconnectedCallback(): void;
28
+ protected initialize(): void;
29
+ protected startAnimation(): void;
30
+ protected createStar(): Particle;
31
+ attributeChangedCallback(name: string, oldValue: string, newValue: string): void;
32
+ }
@@ -0,0 +1,98 @@
1
+ import BB from './BeautifulBackground';
2
+ import Particle from './Particle';
3
+ import { getRandomFloat, interpolateLinear } from '../utils/number';
4
+ import { randomColor } from '../utils/color';
5
+ export class BbStarTrail extends BB {
6
+ constructor() {
7
+ super();
8
+ this.ignoredProps = ['data-characters', 'data-background-color'];
9
+ this.backgroundColor = '0, 0, 0';
10
+ this.starSizeMin = 0.5;
11
+ this.starSizeMax = 1.5;
12
+ this.starSpeedMin = 0.025;
13
+ this.starSpeedMax = 0.05;
14
+ this.starColorHueStart = 30;
15
+ this.starColorHueEnd = 75;
16
+ this.starColorSaturationStart = 100;
17
+ this.starColorSaturationEnd = 100;
18
+ this.starColorLightnessStart = 50;
19
+ this.starColorLightnessEnd = 50;
20
+ this.starRadiusMin = 1;
21
+ this.starRadiusMax = 100;
22
+ this.starLifespanMin = 1000;
23
+ this.starLifespanMax = 10000;
24
+ this.numStars = 1000;
25
+ this.trailOpacity = 0.1;
26
+ }
27
+ connectedCallback() {
28
+ this.shadowR.appendChild(this.canvas);
29
+ this.resizeCanvas();
30
+ this.initialize();
31
+ this.startAnimation();
32
+ window.addEventListener('resize', this.debouncedResizeCanvas.bind(this));
33
+ }
34
+ disconnectedCallback() {
35
+ window.removeEventListener('resize', this.debouncedResizeCanvas.bind(this));
36
+ if (this.animationFrameId !== null) {
37
+ window.cancelAnimationFrame(this.animationFrameId);
38
+ }
39
+ }
40
+ initialize() {
41
+ this.stars = [];
42
+ this.starRadiusMax = Math.max(this.width, this.height) / 2;
43
+ this.animationFrameId = null;
44
+ for (let i = 0; i < this.numStars; i++) {
45
+ this.stars.push(this.createStar());
46
+ }
47
+ }
48
+ startAnimation() {
49
+ const animate = () => {
50
+ this.ctx.fillStyle = `rgba(${this.backgroundColor}, ${this.trailOpacity})`;
51
+ this.ctx.fillRect(0, 0, this.width, this.height);
52
+ this.stars = this.stars.filter((star) => !star.isDead());
53
+ while (this.stars.length < this.numStars) {
54
+ this.stars.push(this.createStar());
55
+ }
56
+ this.stars.forEach((star) => {
57
+ star.update(this.width / 2, this.height / 2);
58
+ star.draw(this.ctx);
59
+ });
60
+ this.animationFrameId = requestAnimationFrame(animate);
61
+ };
62
+ this.animationFrameId = requestAnimationFrame(animate);
63
+ }
64
+ createStar() {
65
+ const size = getRandomFloat(this.starSizeMin, this.starSizeMax);
66
+ const speed = getRandomFloat(interpolateLinear(this.starSpeedMin, -1, 1, -0.04, 0.04), interpolateLinear(this.starSpeedMax, -1, 1, -0.04, 0.04));
67
+ const lifespan = getRandomFloat(this.starLifespanMin, this.starLifespanMax);
68
+ const color = randomColor([this.starColorHueStart, this.starColorHueEnd], [this.starColorSaturationStart, this.starColorSaturationEnd], [this.starColorLightnessStart, this.starColorLightnessEnd]);
69
+ const angle = getRandomFloat(0, Math.PI * 2);
70
+ const radiusRange = this.starRadiusMax - this.starRadiusMin;
71
+ const radius = Math.sqrt(Math.random()) * radiusRange + this.starRadiusMin;
72
+ return new Particle(size, speed, color, radius, angle, lifespan);
73
+ }
74
+ attributeChangedCallback(name, oldValue, newValue) {
75
+ this.setValues(this.ignoredProps, name, oldValue, newValue);
76
+ }
77
+ }
78
+ BbStarTrail.observedAttributes = [
79
+ 'data-background-color',
80
+ 'data-star-size-min',
81
+ 'data-star-size-max',
82
+ 'data-star-speed-min',
83
+ 'data-star-speed-max',
84
+ 'data-star-color-hue-start',
85
+ 'data-star-color-hue-end',
86
+ 'data-star-color-saturation-start',
87
+ 'data-star-color-saturation-end',
88
+ 'data-star-color-lightness-start',
89
+ 'data-star-color-lightness-end',
90
+ 'data-star-radius-min',
91
+ 'data-star-radius-max',
92
+ 'data-star-lifespan-min',
93
+ 'data-star-lifespan-max',
94
+ 'data-num-stars'
95
+ ];
96
+ if (!window.customElements.get('bb-star-trail')) {
97
+ window.customElements.define('bb-star-trail', BbStarTrail);
98
+ }
package/dist/index.d.ts CHANGED
@@ -1 +1,2 @@
1
- export { BbStarField } from './components/StarField';
1
+ export { BbStarTrail } from './components/StarTrail';
2
+ export { BbDigitalRain } from './components/DigitalRain';
package/dist/index.js CHANGED
@@ -1 +1,2 @@
1
- export { BbStarField } from './components/StarField';
1
+ export { BbStarTrail } from './components/StarTrail';
2
+ export { BbDigitalRain } from './components/DigitalRain';
@@ -1,3 +1,3 @@
1
1
  export declare function getRandomFloat(min: number, max: number): number;
2
2
  export declare function getRandomInt(min: number, max: number): number;
3
- export declare function interpolate(value: number, domainStart: number, domainEnd: number, rangeStart: number, rangeEnd: number): number;
3
+ export declare function interpolateLinear(value: number, domainStart: number, domainEnd: number, rangeStart: number, rangeEnd: number): number;
@@ -6,7 +6,7 @@ export function getRandomInt(min, max) {
6
6
  max = Math.floor(max);
7
7
  return Math.floor(Math.random() * (max - min + 1) + min);
8
8
  }
9
- export function interpolate(value, domainStart, domainEnd, rangeStart, rangeEnd) {
9
+ export function interpolateLinear(value, domainStart, domainEnd, rangeStart, rangeEnd) {
10
10
  // Ensure the value is within the domain
11
11
  if (value < domainStart)
12
12
  value = domainStart;
@@ -15,5 +15,6 @@ export function interpolate(value, domainStart, domainEnd, rangeStart, rangeEnd)
15
15
  // Normalize the value within the domain
16
16
  const normalized = (value - domainStart) / (domainEnd - domainStart);
17
17
  // Scale the normalized value to the range and return it
18
+ // The output is always between rangeStart and rangeEnd,
18
19
  return normalized * (rangeEnd - rangeStart) + rangeStart;
19
20
  }
@@ -0,0 +1,3 @@
1
+ export declare function has(object: object, key: string): boolean;
2
+ export declare function isObject(object: unknown): boolean;
3
+ export declare function isEmpty(object: object): boolean;
@@ -0,0 +1,9 @@
1
+ export function has(object, key) {
2
+ return Object.prototype.hasOwnProperty.call(object, key);
3
+ }
4
+ export function isObject(object) {
5
+ return (typeof object === 'object' && Object.prototype.toString.call(object) === '[object Object]');
6
+ }
7
+ export function isEmpty(object) {
8
+ return isObject(object) && Object.keys(object).length === 0;
9
+ }
package/package.json CHANGED
@@ -1,21 +1,42 @@
1
1
  {
2
- "name": "beautiful-backgrounds",
3
- "version": "0.0.1",
4
- "author": "Niekes",
5
- "description": "A helper library to help me build amazing web apps",
6
- "type": "module",
7
- "main": "dist/index.js",
8
- "types": "dist/index.d.ts",
9
- "scripts": {
10
- "clean": "rm -rf dist/components dist/utils/ && rm -f dist/index.js dist/index.d.ts",
11
- "build": "npm run clean && npx tsc",
12
- "watch": "npm run clean && npx tsc --watch",
13
- "release": "npm run clean && npm run build && git push --follow-tags && npm publish"
14
- },
15
- "files": [
16
- "dist/"
17
- ],
18
- "devDependencies": {
19
- "typescript": "5.3.2"
20
- }
2
+ "name": "beautiful-backgrounds",
3
+ "version": "0.0.5",
4
+ "keywords": [
5
+ "canvas",
6
+ "animation",
7
+ "ambient",
8
+ "background",
9
+ "typescript",
10
+ "web-components",
11
+ "background-effects",
12
+ "animated-background",
13
+ "star-field",
14
+ "custom-elements",
15
+ "dynamic-background",
16
+ "visual-effects",
17
+ "interactive-background",
18
+ "canvas-animation",
19
+ "beautiful-backgrounds",
20
+ "html5-canvas"
21
+ ],
22
+ "author": "Niekes (https://niekes.com)",
23
+ "license": "BSD-3-Clause",
24
+ "description": "A collection of customizable web components for creating dynamic, animated backgrounds, featuring a variety of effects including a star field and a digital rain. ",
25
+ "type": "module",
26
+ "main": "dist/index.js",
27
+ "types": "dist/index.d.ts",
28
+ "scripts": {
29
+ "clean": "rm -rf dist",
30
+ "build": "npm run clean && npx tsc && rollup -c",
31
+ "watch": "npm run clean && npx tsc --watch",
32
+ "release": "npm run clean && npm run build && git push --follow-tags && npm publish"
33
+ },
34
+ "files": [
35
+ "dist/"
36
+ ],
37
+ "devDependencies": {
38
+ "@rollup/plugin-terser": "^0.4.4",
39
+ "rollup": "^4.6.1",
40
+ "typescript": "5.3.2"
41
+ }
21
42
  }
@@ -1,14 +0,0 @@
1
- import BB from './BeautifulBackground';
2
- import Star from './particles/Star';
3
- export declare class BbStarField extends BB {
4
- private numStars;
5
- private trailOpacity;
6
- private stars;
7
- private animationFrameId;
8
- constructor();
9
- protected connectedCallback(): void;
10
- protected disconnectedCallback(): void;
11
- protected initialize(): void;
12
- protected startAnimation(): void;
13
- protected createStar(): Star;
14
- }
@@ -1,67 +0,0 @@
1
- import BB from './BeautifulBackground';
2
- import Star from './particles/Star';
3
- import { getRandomFloat } from '../utils/number';
4
- import { randomColor } from '../utils/color';
5
- export class BbStarField extends BB {
6
- constructor() {
7
- super();
8
- }
9
- connectedCallback() {
10
- this.shadowR.appendChild(this.canvas);
11
- this.resizeCanvas();
12
- this.initialize();
13
- this.startAnimation();
14
- window.addEventListener('resize', this.debouncedResizeCanvas.bind(this));
15
- }
16
- disconnectedCallback() {
17
- window.removeEventListener('resize', this.debouncedResizeCanvas.bind(this));
18
- if (this.animationFrameId !== null) {
19
- window.cancelAnimationFrame(this.animationFrameId);
20
- }
21
- }
22
- initialize() {
23
- this.stars = [];
24
- this.numStars = this.parseAttributeToFloat('num-stars') || 100;
25
- this.trailOpacity = 0.1;
26
- this.stars = [];
27
- this.animationFrameId = null;
28
- for (let i = 0; i < this.numStars; i++) {
29
- this.stars.push(this.createStar());
30
- }
31
- }
32
- startAnimation() {
33
- const animate = () => {
34
- this.ctx.fillStyle = `rgba(0, 0, 0, ${this.trailOpacity})`;
35
- this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
36
- this.stars = this.stars.filter((star) => !star.isDead());
37
- while (this.stars.length < this.numStars) {
38
- this.stars.push(this.createStar());
39
- }
40
- this.stars.forEach((star) => {
41
- star.update(this.canvas.width / 2, this.canvas.height / 2);
42
- star.draw(this.ctx);
43
- });
44
- this.animationFrameId = requestAnimationFrame(animate);
45
- };
46
- this.animationFrameId = requestAnimationFrame(animate);
47
- }
48
- createStar() {
49
- const minOrbitRadius = this.parseAttributeToFloat('orbit-radius-min') || 10;
50
- const maxOrbitRadius = this.parseAttributeToFloat('orbit-radius-max') ||
51
- Math.max(this.width, this.height) / 2;
52
- const orbitRange = maxOrbitRadius - minOrbitRadius;
53
- const size = getRandomFloat(this.parseAttributeToInt('star-size-min') || 0.1, this.parseAttributeToInt('star-size-max') || 1.5);
54
- const speed = getRandomFloat(this.parseAttributeToInt('star-speed-min') || 0.001, this.parseAttributeToInt('star-speed-max') || 0.003);
55
- const lifespan = getRandomFloat(this.parseAttributeToInt('star-lifespan-min') || 1000, this.parseAttributeToInt('star-lifespan-max') || 10000);
56
- const color = randomColor([
57
- this.parseAttributeToFloat('star-color-hue-start') || 30,
58
- this.parseAttributeToFloat('star-color-hue-end') || 75
59
- ]);
60
- const angle = getRandomFloat(0, Math.PI * 2);
61
- const orbitRadius = Math.sqrt(Math.random()) * orbitRange + minOrbitRadius;
62
- return new Star(size, speed, lifespan, color, orbitRadius, angle);
63
- }
64
- }
65
- if (!window.customElements.get('bb-star-field')) {
66
- window.customElements.define('bb-star-field', BbStarField);
67
- }
@@ -1,19 +0,0 @@
1
- export default class Star {
2
- orbitRadius: number;
3
- radius: number;
4
- speed: number;
5
- angle: number;
6
- color: string;
7
- born: number;
8
- lifespan: number;
9
- size: number;
10
- x: number;
11
- y: number;
12
- fadeInDuration: number;
13
- fadeOutDuration: number;
14
- constructor(size?: number, speed?: number, lifespan?: number, color?: string, orbitRadius?: number, angle?: number);
15
- update(centerX: number, centerY: number): void;
16
- draw(ctx: CanvasRenderingContext2D): void;
17
- isDead(): boolean;
18
- private calculateOpacity;
19
- }
@@ -1,45 +0,0 @@
1
- export default class Star {
2
- constructor(size = 1, speed = 0.001, lifespan = 1000, color = '#fff', orbitRadius = 100, angle = 0) {
3
- this.size = size;
4
- this.speed = speed;
5
- this.lifespan = lifespan;
6
- this.color = color;
7
- this.orbitRadius = orbitRadius;
8
- this.angle = angle;
9
- this.fadeInDuration = this.lifespan * 0.25;
10
- this.fadeOutDuration = this.lifespan * 0.5;
11
- this.born = Date.now();
12
- this.x = 0;
13
- this.y = 0;
14
- }
15
- update(centerX, centerY) {
16
- this.angle += this.speed;
17
- this.x = centerX + Math.cos(this.angle) * this.orbitRadius;
18
- this.y = centerY + Math.sin(this.angle) * this.orbitRadius;
19
- }
20
- draw(ctx) {
21
- const opacity = this.calculateOpacity();
22
- ctx.beginPath();
23
- ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2, false);
24
- ctx.fillStyle = this.color;
25
- ctx.globalAlpha = opacity;
26
- ctx.shadowBlur = 10;
27
- ctx.shadowColor = this.color;
28
- ctx.fill();
29
- ctx.globalAlpha = 1;
30
- ctx.shadowBlur = 0;
31
- }
32
- isDead() {
33
- return Date.now() - this.born > this.lifespan;
34
- }
35
- calculateOpacity() {
36
- const age = Date.now() - this.born;
37
- if (age < this.fadeInDuration) {
38
- return age / this.fadeInDuration; // Fade in
39
- }
40
- else if (age > this.lifespan - this.fadeOutDuration) {
41
- return (this.lifespan - age) / this.fadeOutDuration; // Fade out
42
- }
43
- return 1; // Fully visible
44
- }
45
- }