sakura.min.js 2.8 KB

1
  1. const Sakura=function(t,e){if(void 0===t)throw new Error("No selector present. Define an element.");var i,a;function n(t){return t[Math.floor(Math.random()*t.length)]}function s(t,e){return Math.floor(Math.random()*(e-t+1))+t}this.el=document.querySelector(t),this.settings=(i={className:"sakura",fallSpeed:1,maxSize:14,minSize:10,delay:300,colors:[{gradientColorStart:"rgba(255, 183, 197, 0.9)",gradientColorEnd:"rgba(255, 197, 208, 0.9)",gradientColorDegree:120}]},a=e,Object.keys(i).forEach((t=>{a&&Object.prototype.hasOwnProperty.call(a,t)&&(i[t]=a[t])})),i),this.el.style.overflowX="hidden";const o=["webkit","moz","MS","o",""];function r(t,e,i){for(let a=0;a<o.length;a+=1){let n=e;o[a]||(n=e.toLowerCase()),t.addEventListener(o[a]+n,i,!1)}}function l(t){return 0<=(t=t.getBoundingClientRect()).top&&0<=t.left&&t.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&t.right<=(window.innerWidth||document.documentElement.clientWidth)}this.createPetal=()=>{this.el.dataset.sakuraAnimId&&setTimeout((()=>{window.requestAnimationFrame(this.createPetal)}),this.settings.delay);const t=n(["blow-soft-left","blow-medium-left","blow-soft-right","blow-medium-right"]),e=n(["sway-0","sway-1","sway-2","sway-3","sway-4","sway-5","sway-6","sway-7","sway-8"]),i=(.007*document.documentElement.clientHeight+Math.round(5*Math.random()))*this.settings.fallSpeed,a=[`fall ${i}s linear 0s 1`,`${t} ${(30<i?i:30)-20+s(0,20)}s linear 0s infinite`,`${e} ${s(2,4)}s linear 0s infinite`].join(", "),o=document.createElement("div");o.classList.add(this.settings.className);var d=s(this.settings.minSize,this.settings.maxSize),m=d-Math.floor(s(0,this.settings.minSize)/3),h=n(this.settings.colors);o.style.background=`linear-gradient(${h.gradientColorDegree}deg, ${h.gradientColorStart}, ${h.gradientColorEnd})`,o.style.webkitAnimation=a,o.style.animation=a,o.style.borderRadius=`${s(this.settings.maxSize,this.settings.maxSize+Math.floor(10*Math.random()))}px ${s(1,Math.floor(m/4))}px`,o.style.height=d+"px",o.style.left=Math.random()*document.documentElement.clientWidth-100+"px",o.style.marginTop=-(Math.floor(20*Math.random())+15)+"px",o.style.width=m+"px",r(o,"AnimationEnd",(()=>{l(o)||o.remove()})),r(o,"AnimationIteration",(()=>{l(o)||o.remove()})),this.el.appendChild(o)},this.el.setAttribute("data-sakura-anim-id",window.requestAnimationFrame(this.createPetal))};Sakura.prototype.start=function(){if(this.el.dataset.sakuraAnimId)throw new Error("Sakura is already running.");this.el.setAttribute("data-sakura-anim-id",window.requestAnimationFrame(this.createPetal))},Sakura.prototype.stop=function(t=!1){var e=this.el.dataset.sakuraAnimId;e&&(window.cancelAnimationFrame(e),this.el.setAttribute("data-sakura-anim-id","")),t||setTimeout((()=>{for(var t=document.getElementsByClassName(this.settings.className);0<t.length;)t[0].parentNode.removeChild(t[0])}),this.settings.delay+50)};