beautiful-backgrounds 0.0.5 → 0.0.7

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
@@ -45,6 +45,10 @@ In browsers with [`esm.sh`][esmsh]:
45
45
  data-star-speed-max="0.003"
46
46
  data-star-color-hue-start="30"
47
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"
48
52
  data-orbit-radius-min="10"
49
53
  data-orbit-radius-max="300"
50
54
  data-star-lifespan-min="1000"
@@ -81,8 +85,12 @@ In browsers with [`esm.sh`][esmsh]:
81
85
  <bb-digital-rain
82
86
  data-characteras="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
83
87
  data-font-size="16"
84
- data-font-color-hue-start="#0F0"
85
- data-font-color-hue-end="#0F0"
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"
86
94
  data-speed="1"
87
95
  ></bb-star-trail>
88
96
  ```
@@ -105,11 +113,7 @@ In browsers with [`esm.sh`][esmsh]:
105
113
  <!-- Links -->
106
114
 
107
115
  [build-badge]: https://github.com/niekes/beautiful-backgrounds/workflows/main/badge.svg
108
-
109
116
  [build]: https://github.com/niekes/beautiful-backgrounds/actions
110
-
111
117
  [esmsh]: https://esm.sh
112
-
113
118
  [npm]: https://www.npmjs.com/package/beautiful-backgrounds
114
-
115
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}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}));
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){this.x=t,this.y=i}update(t,i,s){this.y*s>t&&Math.random()>i?this.y=0:this.y+=1}draw(t,i,s,a){t.fillStyle=s,t.fillText(i,this.x*a,this.y*a)}}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.createSymbols()}createSymbols(){this.columns=Math.floor(this.width/this.fontSize);for(let t=0;t<this.columns;t++)this.symbols[t]=this.createSymbol(t)}updateSymbols(){const t=Math.floor(this.width/this.fontSize);for(let i=this.symbols.length;i<t;i++)this.symbols[i]=this.createSymbol(i);this.symbols.length>t&&(this.symbols.length=t)}animation(){this.updateSymbols(),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)),r([this.fontColorHueStart,this.fontColorHueEnd],[this.fontColorSaturationStart,this.fontColorSaturationEnd],[this.fontColorLightnessStart,this.fontColorLightnessEnd]),this.fontSize),t.update(this.height,this.randomness,this.fontSize)}))}createSymbol(t){return new h(t,e(0,-this.height/this.fontSize))}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,6 +19,7 @@ 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;
18
25
  protected setValues(ignoredProps: string[], name: string, oldValue: string, newValue: string): void;
@@ -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);
@@ -84,6 +103,7 @@ export default class BeautifulBackground extends HTMLElement {
84
103
  this.height = newHeight;
85
104
  this.canvas.width = newWidth;
86
105
  this.canvas.height = newHeight;
106
+ this.canvas.style.backgroundColor = `rgb(${this.backgroundColor})`;
87
107
  }
88
108
  this.fullyInitialized = true;
89
109
  }
@@ -1,6 +1,6 @@
1
1
  import BB from './BeautifulBackground';
2
+ import Symbol from './Symbol';
2
3
  export declare class BbDigitalRain extends BB {
3
- backgroundColor: string;
4
4
  fontSize: number;
5
5
  fontColorHueStart: number;
6
6
  fontColorHueEnd: number;
@@ -9,18 +9,18 @@ export declare class BbDigitalRain extends BB {
9
9
  fontColorLightnessStart: number;
10
10
  fontColorLightnessEnd: number;
11
11
  columns: number;
12
- speed: number;
13
12
  randomness: number;
14
13
  characters: string;
15
- rain: number[];
16
- private trailOpacity;
17
- private animationFrameId;
14
+ symbols: Symbol[];
18
15
  static observedAttributes: string[];
19
16
  protected ignoredProps: string[];
20
17
  constructor();
21
18
  protected connectedCallback(): void;
22
19
  protected disconnectedCallback(): void;
23
20
  protected initialize(): void;
24
- protected startAnimation(): void;
21
+ private createSymbols;
22
+ private updateSymbols;
23
+ protected animation(): void;
24
+ protected createSymbol(index: number): Symbol;
25
25
  attributeChangedCallback(name: string, oldValue: string, newValue: string): void;
26
26
  }
@@ -1,28 +1,27 @@
1
1
  import BB from './BeautifulBackground';
2
2
  import { randomColor } from '../utils/color';
3
+ import Symbol from './Symbol';
4
+ import { getRandomInt } from '../utils/number';
3
5
  export class BbDigitalRain extends BB {
4
6
  constructor() {
5
7
  super();
6
8
  this.ignoredProps = ['data-characters', 'data-background-color'];
7
- this.backgroundColor = '0, 0, 0';
8
9
  this.fontSize = 24;
9
10
  this.fontColorHueStart = 60;
10
- this.fontColorHueEnd = 150;
11
+ this.fontColorHueEnd = this.fontColorHueStart + 90;
11
12
  this.fontColorSaturationStart = 90;
12
13
  this.fontColorSaturationEnd = 100;
13
14
  this.fontColorLightnessStart = 50;
14
15
  this.fontColorLightnessEnd = 50;
15
- this.speed = 2;
16
- this.randomness = 0.9;
16
+ this.randomness = 0.975;
17
17
  this.trailOpacity = 0.1;
18
- this.characters =
19
- 'ヲアウエオカキケコサシスセソタツテナニヌネハヒホマミムメモヤユラリワ13579ヲイクコソチΦトノフヤヨルレロンZ:・."¦=*+-<>|リçδ╘';
18
+ this.characters = 'ヲアウエオカキケコサシスセソタツテナニヌネハヒホマミムメモヤユラリワ13579ヲイクコソチトノフヤヨルレロンZ:."¦=*+-<>|リçδ╘';
20
19
  }
21
20
  connectedCallback() {
22
21
  this.shadowR.appendChild(this.canvas);
23
22
  this.resizeCanvas();
24
23
  this.initialize();
25
- this.startAnimation();
24
+ this.startAnimation(this.animation.bind(this));
26
25
  window.addEventListener('resize', this.debouncedResizeCanvas.bind(this));
27
26
  }
28
27
  disconnectedCallback() {
@@ -32,37 +31,45 @@ export class BbDigitalRain extends BB {
32
31
  }
33
32
  }
34
33
  initialize() {
34
+ this.symbols = [];
35
+ this.createSymbols();
36
+ }
37
+ createSymbols() {
35
38
  this.columns = Math.floor(this.width / this.fontSize);
36
- this.rain = Array(this.columns).fill(this.height);
39
+ for (let i = 0; i < this.columns; i++) {
40
+ this.symbols[i] = this.createSymbol(i);
41
+ }
42
+ }
43
+ updateSymbols() {
44
+ const currentColumns = Math.floor(this.width / this.fontSize);
45
+ for (let i = this.symbols.length; i < currentColumns; i++) {
46
+ this.symbols[i] = this.createSymbol(i);
47
+ }
48
+ if (this.symbols.length > currentColumns) {
49
+ this.symbols.length = currentColumns;
50
+ }
51
+ }
52
+ animation() {
53
+ this.updateSymbols();
54
+ this.ctx.fillStyle = `rgba(${this.backgroundColor}, ${this.trailOpacity})`;
55
+ this.ctx.fillRect(0, 0, this.width, this.height);
56
+ this.ctx.textAlign = 'center';
57
+ this.ctx.font = `${this.fontSize}px monospace`;
58
+ this.symbols.forEach((symbol) => {
59
+ symbol.draw(this.ctx, this.characters.charAt(Math.floor(Math.random() * this.characters.length)), randomColor([this.fontColorHueStart, this.fontColorHueEnd], [this.fontColorSaturationStart, this.fontColorSaturationEnd], [this.fontColorLightnessStart, this.fontColorLightnessEnd]), this.fontSize);
60
+ symbol.update(this.height, this.randomness, this.fontSize);
61
+ });
37
62
  }
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);
63
+ createSymbol(index) {
64
+ return new Symbol(index, getRandomInt(0, -this.height / this.fontSize));
58
65
  }
59
66
  attributeChangedCallback(name, oldValue, newValue) {
60
67
  this.setValues(this.ignoredProps, name, oldValue, newValue);
61
68
  }
62
69
  }
63
70
  BbDigitalRain.observedAttributes = [
71
+ 'data-fps',
64
72
  'data-characters',
65
- 'data-speed',
66
73
  'data-randomness',
67
74
  'data-font-size',
68
75
  'data-font-color-hue-start',
@@ -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
  }
@@ -17,16 +17,14 @@ export declare class BbStarTrail extends BB {
17
17
  starLifespanMin: number;
18
18
  starLifespanMax: number;
19
19
  numStars: number;
20
- private trailOpacity;
21
20
  private stars;
22
- private animationFrameId;
23
21
  static observedAttributes: string[];
24
22
  private ignoredProps;
25
23
  constructor();
26
24
  protected connectedCallback(): void;
27
25
  protected disconnectedCallback(): void;
28
26
  protected initialize(): void;
29
- protected startAnimation(): void;
27
+ protected animation(): void;
30
28
  protected createStar(): Particle;
31
29
  attributeChangedCallback(name: string, oldValue: string, newValue: string): void;
32
30
  }
@@ -28,7 +28,7 @@ export class BbStarTrail extends BB {
28
28
  this.shadowR.appendChild(this.canvas);
29
29
  this.resizeCanvas();
30
30
  this.initialize();
31
- this.startAnimation();
31
+ this.startAnimation(this.animation.bind(this));
32
32
  window.addEventListener('resize', this.debouncedResizeCanvas.bind(this));
33
33
  }
34
34
  disconnectedCallback() {
@@ -45,21 +45,17 @@ export class BbStarTrail extends BB {
45
45
  this.stars.push(this.createStar());
46
46
  }
47
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);
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
+ });
63
59
  }
64
60
  createStar() {
65
61
  const size = getRandomFloat(this.starSizeMin, this.starSizeMax);
@@ -76,6 +72,7 @@ export class BbStarTrail extends BB {
76
72
  }
77
73
  }
78
74
  BbStarTrail.observedAttributes = [
75
+ 'data-fps',
79
76
  'data-background-color',
80
77
  'data-star-size-min',
81
78
  'data-star-size-max',
@@ -0,0 +1,7 @@
1
+ export default class Symbol {
2
+ protected x: number;
3
+ protected y: number;
4
+ constructor(x: number, y: number);
5
+ update(height: number, randomness: number, fontSize: number): void;
6
+ draw(ctx: CanvasRenderingContext2D, text: string, color: string, fontSize: number): void;
7
+ }
@@ -0,0 +1,18 @@
1
+ export default class Symbol {
2
+ constructor(x, y) {
3
+ this.x = x;
4
+ this.y = y;
5
+ }
6
+ update(height, randomness, fontSize) {
7
+ if (this.y * fontSize > height && Math.random() > randomness) {
8
+ this.y = 0;
9
+ }
10
+ else {
11
+ this.y += 1;
12
+ }
13
+ }
14
+ draw(ctx, text, color, fontSize) {
15
+ ctx.fillStyle = color;
16
+ ctx.fillText(text, this.x * fontSize, this.y * fontSize);
17
+ }
18
+ }
package/package.json CHANGED
@@ -1,6 +1,11 @@
1
1
  {
2
2
  "name": "beautiful-backgrounds",
3
- "version": "0.0.5",
3
+ "version": "0.0.7",
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",
@@ -27,6 +32,8 @@
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
  }