beautiful-backgrounds 0.0.2 → 0.0.6

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 CHANGED
@@ -1,7 +1,11 @@
1
1
  # Beautiful Backgrounds
2
2
 
3
+ [![Build][build-badge]][build]
4
+
3
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.
4
6
 
7
+ [EXAMPLES][examples]
8
+
5
9
  ## Features
6
10
 
7
11
  - **Multiple Background Components**: A variety of background components, each offering unique visual effects.
@@ -10,17 +14,30 @@ The "Beautiful Backgrounds" library offers a collection of customizable web comp
10
14
 
11
15
  ## Installation
12
16
 
13
- To include "Beautiful Backgrounds" in your project, add the necessary JavaScript files to your project's scripts or import them directly into your HTML or JavaScript files or run `npm i beautiful-backgrounds --save`
17
+ Using [`npm`][npm]:
14
18
 
15
- ## Usage
19
+ ```sh
20
+ npm i beautiful-backgrounds --save
21
+ ```
16
22
 
17
23
  ```js
18
24
  import { BbStarTrail } from 'beautiful-backgrounds';
19
25
  ```
20
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
+
21
39
  ```html
22
40
  <bb-star-trail
23
- class="bb-star-trail"
24
41
  data-num-stars="567"
25
42
  data-star-size-min="0.1"
26
43
  data-star-size-max="1.5"
@@ -28,6 +45,10 @@ import { BbStarTrail } from 'beautiful-backgrounds';
28
45
  data-star-speed-max="0.003"
29
46
  data-star-color-hue-start="30"
30
47
  data-star-color-hue-end="75"
48
+ data-star-color-saturation-start="90"
49
+ data-star-color-saturation-end="90"
50
+ data-star-color-lightness-start="40"
51
+ data-star-color-lightness-end="60"
31
52
  data-orbit-radius-min="10"
32
53
  data-orbit-radius-max="300"
33
54
  data-star-lifespan-min="1000"
@@ -44,13 +65,55 @@ import { BbStarTrail } from 'beautiful-backgrounds';
44
65
  - `data-star-size-max`: Maximum size of a star.
45
66
  - `data-star-speed-min`: Minimum speed of a star.
46
67
  - `data-star-speed-max`: Maximum speed of a star.
47
- - `data-star-color-hue-start`: Starting hue for star color.
48
- - `data-star-color-hue-end`: Ending hue for star color.
68
+ - `data-star-color-hue-start`: Starting hue for star color. Should be a value between 0 and 360.
69
+ - `data-star-color-hue-end`: Ending hue for star color. Should be a value between 0 and 360.
70
+ - `data-star-color-saturation-start`: Specifies the starting color saturation for star color. Should be a value between 0 and 100.
71
+ - `data-star-color-saturation-start`: Specifies the ending color saturation for star color. Should be a value between 0 and 100.
72
+ - `data-star-color-lightness-start`: Specifies the starting color lightness for star color. Should be a value between 0 and 100.
73
+ - `data-star-color-lightness-start`: Specifies the ending color lightness for star color. Should be a value between 0 and 100.
49
74
  - `data-radius-min`: Minimum radius for star orbit.
50
75
  - `data-radius-max`: Maximum radius for star orbit.
51
76
  - `data-star-lifespan-min`: Minimum lifespan of a star in milliseconds.
52
77
  - `data-star-lifespan-max`: Maximum lifespan of a star in milliseconds.
53
78
  - `data-width`: Width of the star trail component, remove to fit the size of the container
54
79
  - `data-height`: height of the star trail component, remove to fit the size of the container
80
+ - `data-background-color`: Background color of the canvas element
81
+
82
+ ### Digital Rain
83
+
84
+ ```html
85
+ <bb-digital-rain
86
+ data-characteras="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
87
+ data-font-size="16"
88
+ data-font-color-hue-start="60"
89
+ data-font-color-hue-end="150"
90
+ ata-font-color-saturation-start="90"
91
+ ata-font-color-saturation-end="90"
92
+ ata-font-color-lightness-start="40"
93
+ ata-font-color-lightness-end="60"
94
+ data-speed="1"
95
+ ></bb-star-trail>
96
+ ```
97
+
98
+ #### Attributes for bb-digital-rain
99
+
100
+ - `data-characters`: Sets the characters for the digital rain effect.
101
+ - `data-font-size`: Defines the font size of the falling characters.
102
+ - `data-font-color-hue-start`: Specifies the starting color hue for the rain. Should be a value between 0 and 360.
103
+ - `data-font-color-hue-end`: Sets the ending color hue for the rain. Should be a value between 0 and 360.
104
+ - `data-font-color-saturation-start`: Specifies the starting color saturation for the rain. Should be a value between 0 and 100.
105
+ - `data-font-color-saturation-start`: Specifies the ending color saturation for the rain. Should be a value between 0 and 100.
106
+ - `data-font-color-lightness-start`: Specifies the starting color lightness for the rain. Should be a value between 0 and 100.
107
+ - `data-font-color-lightness-start`: Specifies the ending color lightness for the rain. Should be a value between 0 and 100.
108
+ - `data-speed`: Controls the falling speed of the digital rain.
109
+ - `data-background-color`: Background color of the canvas element
55
110
 
56
111
  [![ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/A0A3QJPZ9)
112
+
113
+ <!-- Links -->
114
+
115
+ [build-badge]: https://github.com/niekes/beautiful-backgrounds/workflows/main/badge.svg
116
+ [build]: https://github.com/niekes/beautiful-backgrounds/actions
117
+ [esmsh]: https://esm.sh
118
+ [npm]: https://www.npmjs.com/package/beautiful-backgrounds
119
+ [examples]: https://codepen.io/collection/aMPozo
@@ -1 +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}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.canvas.width=t,this.height=i,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}}class n extends i{constructor(){super(),this.starSizeMin=.1,this.starSizeMax=1.5,this.starSpeedMin=.025,this.starSpeedMax=.05,this.starColorHueStart=30,this.starColorHueEnd=75,this.starRadiusMin=1,this.starRadiusMax=100,this.starLifespanMin=1e3,this.starLifespanMax=1e4,this.numStars=1e3}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.trailOpacity=.1,this.animationFrameId=null;for(let t=0;t<this.numStars;t++)this.stars.push(this.createStar())}startAnimation(){const t=()=>{for(this.ctx.fillStyle=`rgba(0, 0, 0, ${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)),n=s(this.starLifespanMin,this.starLifespanMax),r=function(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])}%)`}([this.starColorHueStart,this.starColorHueEnd]),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,n)}attributeChangedCallback(t,i,s){this.triggerInterpolation(t,i,s)}}n.observedAttributes=["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-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",n),t.BbStarTrail=n}));
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.lastTime=0,this.fps=30,this.timer=0,this.resizeDebounceTimer=null,this.canvas=document.createElement("canvas"),this.ctx=this.canvas.getContext("2d"),this.backgroundColor="0, 0, 0"}debouncedResizeCanvas(){clearTimeout(this.resizeDebounceTimer),this.resizeDebounceTimer=setTimeout((()=>{this.resizeCanvas()}),1e3)}startAnimation(t){const i=s=>{const a=s-this.lastTime;this.lastTime=s,this.timer>1e3/this.fps?(t(),this.timer=0):this.timer+=a,this.animationFrameId=requestAnimationFrame(i)};this.animationFrameId=requestAnimationFrame(i)}interpolateWithThrottle(t,i,s,a,e){const n=Math.ceil(s/a),r=(i-t)/n;let o=t,h=0,l=!0,d=null;!function t(){h<s&&l?(e(o,!1),o+=r,h+=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),n=this.getPropNameCamelCased(t);var r,o;a!==e&&this.fullyInitialized?(r=this,o=n,Object.prototype.hasOwnProperty.call(r,o)&&this.interpolateWithThrottle(i?a:this[n],e,this.interpolationDuration,this.interpolationStep,(t=>{this[n]=t}))):this[n]=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.canvas.style.backgroundColor=`rgb(${this.backgroundColor})`),this.fullyInitialized=!0}}class s{constructor(t,i,s,a,e,n){this.size=t,this.speed=i,this.color=s,this.radius=a,this.angle=e,this.lifespan=n,this.x=0,this.y=0,this.born=Date.now(),this.fadeInDuration=.25*this.lifespan,this.fadeOutDuration=.5*this.lifespan}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}draw(t){t.beginPath(),t.arc(this.x,this.y,this.size,0,2*Math.PI,!1),t.fillStyle=this.color,t.globalAlpha=this.calculateOpacity(),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 a(t,i){return Math.random()*(i-t)+t}function e(t,i){return t=Math.ceil(t),i=Math.floor(i),Math.floor(Math.random()*(i-t+1)+t)}function n(t,i,s,a,e){t<i&&(t=i),t>s&&(t=s);return(t-i)/(s-i)*(e-a)+a}function r(t=[0,360],i=[0,100],s=[40,60]){return`hsl(${e(t[0],t[1])}, ${e(i[0],i[1])}%, ${e(s[0],s[1])}%)`}class o 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(this.animation.bind(this)),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())}animation(){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)}))}createStar(){const t=a(this.starSizeMin,this.starSizeMax),i=a(n(this.starSpeedMin,-1,1,-.04,.04),n(this.starSpeedMax,-1,1,-.04,.04)),e=a(this.starLifespanMin,this.starLifespanMax),o=r([this.starColorHueStart,this.starColorHueEnd],[this.starColorSaturationStart,this.starColorSaturationEnd],[this.starColorLightnessStart,this.starColorLightnessEnd]),h=a(0,2*Math.PI),l=this.starRadiusMax-this.starRadiusMin,d=Math.sqrt(Math.random())*l+this.starRadiusMin;return new s(t,i,o,d,h,e)}attributeChangedCallback(t,i,s){this.setValues(this.ignoredProps,t,i,s)}}o.observedAttributes=["data-fps","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",o);class h{constructor(t,i,s,a="#0f0"){this.x=t,this.y=i,this.fontSize=s,this.color=a}update(t,i){this.y*this.fontSize>t&&Math.random()>i?this.y=0:this.y+=1}draw(t,i){t.fillStyle=this.color,t.fillText(i,this.x*this.fontSize,this.y*this.fontSize)}}class l extends i{constructor(){super(),this.ignoredProps=["data-characters","data-background-color"],this.fontSize=24,this.fontColorHueStart=60,this.fontColorHueEnd=this.fontColorHueStart+90,this.fontColorSaturationStart=90,this.fontColorSaturationEnd=100,this.fontColorLightnessStart=50,this.fontColorLightnessEnd=50,this.randomness=.975,this.trailOpacity=.1,this.characters='ヲアウエオカキケコサシスセソタツテナニヌネハヒホマミムメモヤユラリワ13579ヲイクコソチトノフヤヨルレロンZ:."¦=*+-<>|リçδ╘'}connectedCallback(){this.shadowR.appendChild(this.canvas),this.resizeCanvas(),this.initialize(),this.startAnimation(this.animation.bind(this)),window.addEventListener("resize",this.debouncedResizeCanvas.bind(this))}disconnectedCallback(){window.removeEventListener("resize",this.debouncedResizeCanvas.bind(this)),null!==this.animationFrameId&&window.cancelAnimationFrame(this.animationFrameId)}initialize(){this.symbols=[],this.columns=Math.floor(this.width/this.fontSize);for(let t=0;t<this.columns;t++)this.symbols[t]=this.createSymbol(t)}animation(){this.ctx.fillStyle=`rgba(${this.backgroundColor}, ${this.trailOpacity})`,this.ctx.fillRect(0,0,this.width,this.height),this.ctx.textAlign="center",this.ctx.font=`${this.fontSize}px monospace`,this.symbols.forEach((t=>{t.draw(this.ctx,this.characters.charAt(Math.floor(Math.random()*this.characters.length))),t.update(this.height,this.randomness)}))}createSymbol(t){return new h(t,e(0,-this.height/this.fontSize),this.fontSize,r([this.fontColorHueStart,this.fontColorHueEnd],[this.fontColorSaturationStart,this.fontColorSaturationEnd],[this.fontColorLightnessStart,this.fontColorLightnessEnd]))}attributeChangedCallback(t,i,s){this.setValues(this.ignoredProps,t,i,s)}}l.observedAttributes=["data-fps","data-characters","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",l),t.BbDigitalRain=l,t.BbStarTrail=o}));
@@ -4,6 +4,12 @@ export default abstract class BeautifulBackground extends HTMLElement {
4
4
  protected height: number;
5
5
  protected canvas: HTMLCanvasElement;
6
6
  protected ctx: CanvasRenderingContext2D;
7
+ protected backgroundColor: string;
8
+ protected trailOpacity: number;
9
+ protected lastTime: number;
10
+ protected fps: number;
11
+ protected timer: number;
12
+ protected animationFrameId: number | null;
7
13
  private resizeDebounceTimer;
8
14
  private interpolationDuration;
9
15
  private interpolationStep;
@@ -13,8 +19,10 @@ export default abstract class BeautifulBackground extends HTMLElement {
13
19
  protected abstract disconnectedCallback(): void;
14
20
  protected abstract initialize(): void;
15
21
  protected debouncedResizeCanvas(): void;
22
+ protected startAnimation(fn: Function): void;
16
23
  protected interpolateWithThrottle(startValue: number, newValue: number, durationMs: number, throttleMs: number, onInterpolate: Function): void;
17
24
  protected triggerInterpolation(name: string, oldValue: string, newValue: string): void;
25
+ protected setValues(ignoredProps: string[], name: string, oldValue: string, newValue: string): void;
18
26
  protected getPropNameCamelCased(dashCased: string): string;
19
27
  protected resizeCanvas(): void;
20
28
  }
@@ -13,15 +13,34 @@ export default class BeautifulBackground extends HTMLElement {
13
13
  }
14
14
  </style>
15
15
  `;
16
+ this.lastTime = 0;
17
+ this.fps = 30;
18
+ this.timer = 0;
16
19
  this.resizeDebounceTimer = null;
17
20
  this.canvas = document.createElement('canvas');
18
21
  this.ctx = this.canvas.getContext('2d');
22
+ this.backgroundColor = '0, 0, 0';
19
23
  }
20
24
  debouncedResizeCanvas() {
21
25
  clearTimeout(this.resizeDebounceTimer);
22
26
  this.resizeDebounceTimer = setTimeout(() => {
23
27
  this.resizeCanvas();
24
- }, 1000); // Adjust the debounce time as needed
28
+ }, 1000);
29
+ }
30
+ startAnimation(fn) {
31
+ const animate = (timeStamp) => {
32
+ const deltaTime = timeStamp - this.lastTime;
33
+ this.lastTime = timeStamp;
34
+ if (this.timer > 1000 / this.fps) {
35
+ fn();
36
+ this.timer = 0;
37
+ }
38
+ else {
39
+ this.timer += deltaTime;
40
+ }
41
+ this.animationFrameId = requestAnimationFrame(animate);
42
+ };
43
+ this.animationFrameId = requestAnimationFrame(animate);
25
44
  }
26
45
  interpolateWithThrottle(startValue, newValue, durationMs, throttleMs, onInterpolate) {
27
46
  const numSteps = Math.ceil(durationMs / throttleMs);
@@ -62,6 +81,15 @@ export default class BeautifulBackground extends HTMLElement {
62
81
  this[prop] = target;
63
82
  }
64
83
  }
84
+ setValues(ignoredProps, name, oldValue, newValue) {
85
+ if (ignoredProps.includes(name)) {
86
+ const propName = this.getPropNameCamelCased(name);
87
+ this[propName] = newValue;
88
+ }
89
+ if (!ignoredProps.includes(name)) {
90
+ this.triggerInterpolation(name, oldValue, newValue);
91
+ }
92
+ }
65
93
  getPropNameCamelCased(dashCased) {
66
94
  return dashCased
67
95
  .substring(5)
@@ -72,9 +100,10 @@ export default class BeautifulBackground extends HTMLElement {
72
100
  const newHeight = Number.parseInt(this.getAttribute('data-height')) || this.parentElement.clientHeight;
73
101
  if (newWidth !== this.width || newHeight !== this.height) {
74
102
  this.width = newWidth;
75
- this.canvas.width = newWidth;
76
103
  this.height = newHeight;
104
+ this.canvas.width = newWidth;
77
105
  this.canvas.height = newHeight;
106
+ this.canvas.style.backgroundColor = `rgb(${this.backgroundColor})`;
78
107
  }
79
108
  this.fullyInitialized = true;
80
109
  }
@@ -0,0 +1,24 @@
1
+ import BB from './BeautifulBackground';
2
+ import Symbol from './Symbol';
3
+ export declare class BbDigitalRain extends BB {
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
+ randomness: number;
13
+ characters: string;
14
+ symbols: Symbol[];
15
+ static observedAttributes: string[];
16
+ protected ignoredProps: string[];
17
+ constructor();
18
+ protected connectedCallback(): void;
19
+ protected disconnectedCallback(): void;
20
+ protected initialize(): void;
21
+ protected animation(): void;
22
+ protected createSymbol(index: number): Symbol;
23
+ attributeChangedCallback(name: string, oldValue: string, newValue: string): void;
24
+ }
@@ -0,0 +1,72 @@
1
+ import BB from './BeautifulBackground';
2
+ import { randomColor } from '../utils/color';
3
+ import Symbol from './Symbol';
4
+ import { getRandomInt } from '../utils/number';
5
+ export class BbDigitalRain extends BB {
6
+ constructor() {
7
+ super();
8
+ this.ignoredProps = ['data-characters', 'data-background-color'];
9
+ this.fontSize = 24;
10
+ this.fontColorHueStart = 60;
11
+ this.fontColorHueEnd = this.fontColorHueStart + 90;
12
+ this.fontColorSaturationStart = 90;
13
+ this.fontColorSaturationEnd = 100;
14
+ this.fontColorLightnessStart = 50;
15
+ this.fontColorLightnessEnd = 50;
16
+ this.randomness = 0.975;
17
+ this.trailOpacity = 0.1;
18
+ this.characters = 'ヲアウエオカキケコサシスセソタツテナニヌネハヒホマミムメモヤユラリワ13579ヲイクコソチトノフヤヨルレロンZ:."¦=*+-<>|リçδ╘';
19
+ }
20
+ connectedCallback() {
21
+ this.shadowR.appendChild(this.canvas);
22
+ this.resizeCanvas();
23
+ this.initialize();
24
+ this.startAnimation(this.animation.bind(this));
25
+ window.addEventListener('resize', this.debouncedResizeCanvas.bind(this));
26
+ }
27
+ disconnectedCallback() {
28
+ window.removeEventListener('resize', this.debouncedResizeCanvas.bind(this));
29
+ if (this.animationFrameId !== null) {
30
+ window.cancelAnimationFrame(this.animationFrameId);
31
+ }
32
+ }
33
+ initialize() {
34
+ this.symbols = [];
35
+ this.columns = Math.floor(this.width / this.fontSize);
36
+ for (let i = 0; i < this.columns; i++) {
37
+ this.symbols[i] = this.createSymbol(i);
38
+ }
39
+ }
40
+ animation() {
41
+ this.ctx.fillStyle = `rgba(${this.backgroundColor}, ${this.trailOpacity})`;
42
+ this.ctx.fillRect(0, 0, this.width, this.height);
43
+ this.ctx.textAlign = 'center';
44
+ this.ctx.font = `${this.fontSize}px monospace`;
45
+ this.symbols.forEach((symbol) => {
46
+ symbol.draw(this.ctx, this.characters.charAt(Math.floor(Math.random() * this.characters.length)));
47
+ symbol.update(this.height, this.randomness);
48
+ });
49
+ }
50
+ createSymbol(index) {
51
+ return new Symbol(index, getRandomInt(0, -this.height / this.fontSize), this.fontSize, randomColor([this.fontColorHueStart, this.fontColorHueEnd], [this.fontColorSaturationStart, this.fontColorSaturationEnd], [this.fontColorLightnessStart, this.fontColorLightnessEnd]));
52
+ }
53
+ attributeChangedCallback(name, oldValue, newValue) {
54
+ this.setValues(this.ignoredProps, name, oldValue, newValue);
55
+ }
56
+ }
57
+ BbDigitalRain.observedAttributes = [
58
+ 'data-fps',
59
+ 'data-characters',
60
+ 'data-randomness',
61
+ 'data-font-size',
62
+ 'data-font-color-hue-start',
63
+ 'data-font-color-hue-end',
64
+ 'data-font-color-saturation-start',
65
+ 'data-font-color-saturation-end',
66
+ 'data-font-color-lightness-start',
67
+ 'data-font-color-lightness-end',
68
+ 'data-background-color'
69
+ ];
70
+ if (!window.customElements.get('bb-digital-rain')) {
71
+ window.customElements.define('bb-digital-rain', BbDigitalRain);
72
+ }
@@ -10,24 +10,8 @@ export default class Particle {
10
10
  private born;
11
11
  private fadeInDuration;
12
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
13
  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
14
  update(centerX: number, centerY: number): void;
30
- ellipticalMotion(centerX: number, centerY: number): void;
31
15
  draw(ctx: CanvasRenderingContext2D): void;
32
16
  isDead(): boolean;
33
17
  private calculateOpacity;
@@ -1,17 +1,5 @@
1
- import { getRandomInt, getRandomFloat } from '../utils/number';
2
1
  export default class Particle {
3
2
  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
3
  this.size = size;
16
4
  this.speed = speed;
17
5
  this.color = color;
@@ -24,58 +12,16 @@ export default class Particle {
24
12
  this.fadeInDuration = this.lifespan * 0.25;
25
13
  this.fadeOutDuration = this.lifespan * 0.5;
26
14
  }
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
15
  update(centerX, centerY) {
64
16
  this.angle += this.speed;
65
17
  this.x = centerX + Math.cos(this.angle) * this.radius;
66
18
  this.y = centerY + Math.sin(this.angle) * this.radius;
67
19
  }
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
20
  draw(ctx) {
74
- const opacity = this.calculateOpacity();
75
21
  ctx.beginPath();
76
22
  ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2, false);
77
23
  ctx.fillStyle = this.color;
78
- ctx.globalAlpha = opacity;
24
+ ctx.globalAlpha = this.calculateOpacity();
79
25
  ctx.shadowBlur = 10;
80
26
  ctx.shadowColor = this.color;
81
27
  ctx.fill();
@@ -88,11 +34,11 @@ export default class Particle {
88
34
  calculateOpacity() {
89
35
  const age = Date.now() - this.born;
90
36
  if (age < this.fadeInDuration) {
91
- return age / this.fadeInDuration; // Fade in
37
+ return age / this.fadeInDuration;
92
38
  }
93
- else if (age > this.lifespan - this.fadeOutDuration) {
94
- return (this.lifespan - age) / this.fadeOutDuration; // Fade out
39
+ if (age > this.lifespan - this.fadeOutDuration) {
40
+ return (this.lifespan - age) / this.fadeOutDuration;
95
41
  }
96
- return 1; // Fully visible
42
+ return 1;
97
43
  }
98
44
  }
@@ -1,26 +1,30 @@
1
1
  import BB from './BeautifulBackground';
2
2
  import Particle from './Particle';
3
3
  export declare class BbStarTrail extends BB {
4
- private starSizeMin;
5
- private starSizeMax;
6
- private starSpeedMin;
7
- private starSpeedMax;
8
- private starColorHueStart;
9
- private starColorHueEnd;
10
- private starRadiusMin;
11
- private starRadiusMax;
12
- private starLifespanMin;
13
- private starLifespanMax;
14
- private numStars;
15
- private trailOpacity;
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;
16
20
  private stars;
17
- private animationFrameId;
18
21
  static observedAttributes: string[];
22
+ private ignoredProps;
19
23
  constructor();
20
24
  protected connectedCallback(): void;
21
25
  protected disconnectedCallback(): void;
22
26
  protected initialize(): void;
23
- protected startAnimation(): void;
27
+ protected animation(): void;
24
28
  protected createStar(): Particle;
25
29
  attributeChangedCallback(name: string, oldValue: string, newValue: string): void;
26
30
  }
@@ -5,23 +5,30 @@ import { randomColor } from '../utils/color';
5
5
  export class BbStarTrail extends BB {
6
6
  constructor() {
7
7
  super();
8
- this.starSizeMin = 0.1;
8
+ this.ignoredProps = ['data-characters', 'data-background-color'];
9
+ this.backgroundColor = '0, 0, 0';
10
+ this.starSizeMin = 0.5;
9
11
  this.starSizeMax = 1.5;
10
12
  this.starSpeedMin = 0.025;
11
13
  this.starSpeedMax = 0.05;
12
14
  this.starColorHueStart = 30;
13
15
  this.starColorHueEnd = 75;
16
+ this.starColorSaturationStart = 100;
17
+ this.starColorSaturationEnd = 100;
18
+ this.starColorLightnessStart = 50;
19
+ this.starColorLightnessEnd = 50;
14
20
  this.starRadiusMin = 1;
15
21
  this.starRadiusMax = 100;
16
22
  this.starLifespanMin = 1000;
17
23
  this.starLifespanMax = 10000;
18
24
  this.numStars = 1000;
25
+ this.trailOpacity = 0.1;
19
26
  }
20
27
  connectedCallback() {
21
28
  this.shadowR.appendChild(this.canvas);
22
29
  this.resizeCanvas();
23
30
  this.initialize();
24
- this.startAnimation();
31
+ this.startAnimation(this.animation.bind(this));
25
32
  window.addEventListener('resize', this.debouncedResizeCanvas.bind(this));
26
33
  }
27
34
  disconnectedCallback() {
@@ -33,49 +40,50 @@ export class BbStarTrail extends BB {
33
40
  initialize() {
34
41
  this.stars = [];
35
42
  this.starRadiusMax = Math.max(this.width, this.height) / 2;
36
- this.trailOpacity = 0.1;
37
43
  this.animationFrameId = null;
38
44
  for (let i = 0; i < this.numStars; i++) {
39
45
  this.stars.push(this.createStar());
40
46
  }
41
47
  }
42
- startAnimation() {
43
- const animate = () => {
44
- this.ctx.fillStyle = `rgba(0, 0, 0, ${this.trailOpacity})`;
45
- this.ctx.fillRect(0, 0, this.width, this.height);
46
- this.stars = this.stars.filter((star) => !star.isDead());
47
- while (this.stars.length < this.numStars) {
48
- this.stars.push(this.createStar());
49
- }
50
- this.stars.forEach((star) => {
51
- star.update(this.width / 2, this.height / 2);
52
- star.draw(this.ctx);
53
- });
54
- this.animationFrameId = requestAnimationFrame(animate);
55
- };
56
- this.animationFrameId = requestAnimationFrame(animate);
48
+ animation() {
49
+ this.ctx.fillStyle = `rgba(${this.backgroundColor}, ${this.trailOpacity})`;
50
+ this.ctx.fillRect(0, 0, this.width, this.height);
51
+ this.stars = this.stars.filter((star) => !star.isDead());
52
+ while (this.stars.length < this.numStars) {
53
+ this.stars.push(this.createStar());
54
+ }
55
+ this.stars.forEach((star) => {
56
+ star.update(this.width / 2, this.height / 2);
57
+ star.draw(this.ctx);
58
+ });
57
59
  }
58
60
  createStar() {
59
61
  const size = getRandomFloat(this.starSizeMin, this.starSizeMax);
60
62
  const speed = getRandomFloat(interpolateLinear(this.starSpeedMin, -1, 1, -0.04, 0.04), interpolateLinear(this.starSpeedMax, -1, 1, -0.04, 0.04));
61
63
  const lifespan = getRandomFloat(this.starLifespanMin, this.starLifespanMax);
62
- const color = randomColor([this.starColorHueStart, this.starColorHueEnd]);
64
+ const color = randomColor([this.starColorHueStart, this.starColorHueEnd], [this.starColorSaturationStart, this.starColorSaturationEnd], [this.starColorLightnessStart, this.starColorLightnessEnd]);
63
65
  const angle = getRandomFloat(0, Math.PI * 2);
64
66
  const radiusRange = this.starRadiusMax - this.starRadiusMin;
65
67
  const radius = Math.sqrt(Math.random()) * radiusRange + this.starRadiusMin;
66
68
  return new Particle(size, speed, color, radius, angle, lifespan);
67
69
  }
68
70
  attributeChangedCallback(name, oldValue, newValue) {
69
- this.triggerInterpolation(name, oldValue, newValue);
71
+ this.setValues(this.ignoredProps, name, oldValue, newValue);
70
72
  }
71
73
  }
72
74
  BbStarTrail.observedAttributes = [
75
+ 'data-fps',
76
+ 'data-background-color',
73
77
  'data-star-size-min',
74
78
  'data-star-size-max',
75
79
  'data-star-speed-min',
76
80
  'data-star-speed-max',
77
81
  'data-star-color-hue-start',
78
82
  'data-star-color-hue-end',
83
+ 'data-star-color-saturation-start',
84
+ 'data-star-color-saturation-end',
85
+ 'data-star-color-lightness-start',
86
+ 'data-star-color-lightness-end',
79
87
  'data-star-radius-min',
80
88
  'data-star-radius-max',
81
89
  'data-star-lifespan-min',
@@ -0,0 +1,9 @@
1
+ export default class Symbol {
2
+ protected x: number;
3
+ protected y: number;
4
+ protected fontSize: number;
5
+ protected color: string;
6
+ constructor(x: number, y: number, fontSize: number, color?: string);
7
+ update(height: number, randomness: number): void;
8
+ draw(ctx: CanvasRenderingContext2D, text: string): void;
9
+ }
@@ -0,0 +1,20 @@
1
+ export default class Symbol {
2
+ constructor(x, y, fontSize, color = '#0f0') {
3
+ this.x = x;
4
+ this.y = y;
5
+ this.fontSize = fontSize;
6
+ this.color = color;
7
+ }
8
+ update(height, randomness) {
9
+ if (this.y * this.fontSize > height && Math.random() > randomness) {
10
+ this.y = 0;
11
+ }
12
+ else {
13
+ this.y += 1;
14
+ }
15
+ }
16
+ draw(ctx, text) {
17
+ ctx.fillStyle = this.color;
18
+ ctx.fillText(text, this.x * this.fontSize, this.y * this.fontSize);
19
+ }
20
+ }
package/dist/index.d.ts CHANGED
@@ -1 +1,2 @@
1
1
  export { BbStarTrail } from './components/StarTrail';
2
+ export { BbDigitalRain } from './components/DigitalRain';
package/dist/index.js CHANGED
@@ -1 +1,2 @@
1
1
  export { BbStarTrail } from './components/StarTrail';
2
+ export { BbDigitalRain } from './components/DigitalRain';
package/package.json CHANGED
@@ -1,6 +1,11 @@
1
1
  {
2
2
  "name": "beautiful-backgrounds",
3
- "version": "0.0.2",
3
+ "version": "0.0.6",
4
+ "repository": {
5
+ "type": "git",
6
+ "url": "https://github.com/Niekes/beautiful-backgrounds"
7
+ },
8
+ "homepage": "https://github.com/Niekes/beautiful-backgrounds#readme",
4
9
  "keywords": [
5
10
  "canvas",
6
11
  "animation",
@@ -21,12 +26,14 @@
21
26
  ],
22
27
  "author": "Niekes (https://niekes.com)",
23
28
  "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.",
29
+ "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
30
  "type": "module",
26
31
  "main": "dist/index.js",
27
32
  "types": "dist/index.d.ts",
28
33
  "scripts": {
29
34
  "clean": "rm -rf dist",
35
+ "pretest": "npx tsc",
36
+ "test": "c8 --reporter lcov tape tests/**/*.js",
30
37
  "build": "npm run clean && npx tsc && rollup -c",
31
38
  "watch": "npm run clean && npx tsc --watch",
32
39
  "release": "npm run clean && npm run build && git push --follow-tags && npm publish"
@@ -36,7 +43,9 @@
36
43
  ],
37
44
  "devDependencies": {
38
45
  "@rollup/plugin-terser": "^0.4.4",
46
+ "c8": "^8.0.1",
39
47
  "rollup": "^4.6.1",
48
+ "tape": "^5.7.2",
40
49
  "typescript": "5.3.2"
41
50
  }
42
51
  }