50projects50days 模糊加载blurry loading
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>blurry-loading</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
overflow: hidden;
}
.bg {
position: absolute;
background: url(https://images.unsplash.com/photo-1576161787924-01bb08dad4a4?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2104&q=80) no-repeat center center/cover;
filter: blur(0px);
z-index: -1;
/* blur滤镜会导致图片边界出现白色区域,将图片扩大可以改善 */
top:-30px;
left:-30px;
width: calc(100vw + 60px);
height: calc(100vh + 60px);
}
.load {
font-size: 2rem;
color: #fff;
font-weight: bold;
user-select: none;
}
</style>
</head>
<body>
<section class="bg"></section>
<p class="load">0%</p>
</body>
<script>
// 获取文字和背景图片
const loadText = document.querySelector('.load');
const bg = document.querySelector('.bg');
//load表示当前进度的百分比数字
let load = 0;
// setInterval:进度不断增加,并渲染进度数字和背景模糊程度
const int = setInterval(loading, 20);
function loading() {
load++;
//如果进度到达100,表示进度完成,不用增加了。
if (load > 99) {
clearInterval(int);
}
//修改进度百分数
loadText.innerText = `${load}%`;
//修改数字的透明度:具体表现为文字逐渐隐形
loadText.style.opacity = scale(load, 0, 100, 1, 0);
//修改背景图片的模糊程度
bg.style.filter = `blur(${scale(load,0,100,30,0)}px)`;
}
//https://stackoverflow.com/questions/10756313/javascript-jquery-map-a-range-of-numbers-to-another-range-of-numbers
//获取 一个在某范围内的值 映射到 另一个范围时 对应的值。
function scale(num, inMin, inMax, outMin, outMax) {
return ((num - inMin) * (outMax - outMin)) / (inMax - inMin) + outMin;
}
</script>
</html>