From 2a4cd3c3b364d2f9b485a025cf9c0db78cdec5e4 Mon Sep 17 00:00:00 2001 From: flashwave Date: Thu, 20 May 2021 22:08:26 +0200 Subject: [PATCH] Add fade transition to background changes. --- public/now.css | 13 ++++++++++ public/now.js | 64 ++++++++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 75 insertions(+), 2 deletions(-) diff --git a/public/now.css b/public/now.css index b2d9bc4..e355896 100644 --- a/public/now.css +++ b/public/now.css @@ -2,6 +2,8 @@ margin: 0; padding: 0; box-sizing: border-box; + position: relative; + outline-style: none; } html, @@ -77,8 +79,19 @@ a:focus { height: 100%; width: 100%; transition: background-color 2.1s; +} +.background img { + width: 100%; + height: 100%; + object-fit: cover; filter: blur(10px); transform: scale(1.2); + position: absolute; + top: 0; + left: 0; + will-change: z-index, opacity; + opacity: 1; + transition: opacity .5s; } .index__title { diff --git a/public/now.js b/public/now.js index 06c3b5b..226b214 100644 --- a/public/now.js +++ b/public/now.js @@ -9,6 +9,8 @@ var fnp = { }, ui: { mode: '', + bgSwitch: false, + currBg: '', }, }; @@ -128,13 +130,71 @@ fnp.ui.setBackground = function(bgPath) { } this.eBg.style.backgroundColor = null; - this.eBg.style.backgroundImage = 'url(\'' + (bgPath || '').toString() + '\')'; + this.switchBackground(bgPath); +}; +fnp.ui.switchBackground = function(bgPath) { + if(bgPath === this.currBg) + return; + this.currBg = bgPath; + + if(this.bgSwitch) { + setTimeout(this.switchBackground.bind(this, bgPath), 1000); + return; + } + this.bgSwitch = true; + + while(this.eBg.children.length > 2) + this.eBg.removeChild(eBg.firstChild); + + var newBg = null, + hasNewBg = !!bgPath, + oldBg = this.eBg.firstChild, + hasOldBg = !!oldBg; + + if(hasOldBg) + oldBg.style.zIndex = '-1'; + + if(hasNewBg) { + newBg = document.createElement('img'); + newBg.alt = newBg.src = bgPath; + newBg.style.opacity = '0'; + newBg.style.zIndex = '1'; + newBg.onload = function() { + setTimeout(function() { + newBg.style.opacity = null; + setTimeout(function() { + newBg.style.zIndex = null; + if(hasOldBg) + this.eBg.removeChild(oldBg); + this.bgSwitch = false; + }.bind(this), 500); + }.bind(this), 50); + }.bind(this); + newBg.onerror = function() { + this.eBg.removeChild(newBg); + newBg = null; + hasNewBg = false; + this.bgSwitch = false; + }.bind(this); + this.eBg.appendChild(newBg); + } else if(hasOldBg) { + oldBg.style.opacity = '0'; + setTimeout(function() { + this.eBg.removeChild(oldBg); + this.bgSwitch = false; + }.bind(this), 500); + } else { + this.bgSwitch = false; + } +}; +fnp.ui.removeBackground = function() { + this.switchBackground(''); }; fnp.ui.setBackgroundFade = function() { if(this.iColourFade !== 0) return; - this.eBg.style.backgroundImage = null; + this.removeBackground(); var fader = function() { var colour = Math.floor(Math.random() * 0xFFFFFF).toString(16);