HTML:
<div class="container">
<h1>HELLO WORLD!</h1>
</div>
CSS:
/* 引入谷歌字体 */
@import url("http://fonts.googleapis.com/css?family=Righteous");
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
body{
width: 100vw;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
font-family: 'Righteous';
font-weight: bold;
--bg:#131313;
background-color: var(--bg);
}
.container{
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
--x:1;
--y:1;
}
h1{
font-size: 5vw;
color: var(--bg);
text-align: center;
text-shadow: -1px -1px 0 #fff,1px 1px 0 #fff,1px -1px 0 #fff,-1px 1px 0 #fff,
calc(var(--x) * -0.1vw) calc(var(--y) * -0.1vw) 0px hsl(calc(var(--x) + var(--y) * 11) 30% 50% / 40%),
calc(var(--x) * -0.2vw) calc(var(--y) * -0.2vw) 1px hsl(calc(var(--x) + var(--y) * 12) 30% 50% / 36%),
calc(var(--x) * -0.3vw) calc(var(--y) * -0.3vw) 2px hsl(calc(var(--x) + var(--y) * 13) 30% 50% / 32%),
calc(var(--x) * -0.4vw) calc(var(--y) * -0.4vw) 3px hsl(calc(var(--x) + var(--y) * 14) 30% 50% / 28%),
calc(var(--x) * -0.5vw) calc(var(--y) * -0.5vw) 4px hsl(calc(var(--x) + var(--y) * 15) 30% 50% / 24%),
calc(var(--x) * -0.6vw) calc(var(--y) * -0.6vw) 5px hsl(calc(var(--x) + var(--y) * 16) 30% 50% / 20%),
calc(var(--x) * -0.7vw) calc(var(--y) * -0.7vw) 6px hsl(calc(var(--x) + var(--y) * 17) 30% 50% / 16%),
calc(var(--x) * -0.8vw) calc(var(--y) * -0.8vw) 7px hsl(calc(var(--x) + var(--y) * 18) 30% 50% / 12%);
}
JS:
// 容器
const container=document.querySelector('.container');
// 获取当前坐标
function getCursorPosition(event,rect,divider=20){
const x=event.clientX - rect.left;
const y=event.clientY - rect.top;
const res={
x:(x - rect.width / 2) / divider,
y:(y - rect.height / 2) / divider
};
return res;
}
// 根据日期计算获取数字
function getNumbersFromDate(){
const startDate=new Date(); //存储初始日期
function updateNumbers(){
const currentDate=new Date();
const timeDiff=currentDate - startDate;
// 根据时差计算出数字
const number1=Math.sin(timeDiff / 400);
const number2=Math.cos(timeDiff / 400);
// 将数字作为对象返回
return {
number1,
number2
}
}
// 更新坐标
function updateElementPosition(x,y){
container.style.setProperty('--x',x);
container.style.setProperty('--y',y);
}
// 绘制动画
function animationLoop(){
// 判断当前DOM节点是否能完全匹配对应的CSS的hover选择器
const isHovered=container.matches(':hover');
const rect=container.getBoundingClientRect();
if(isHovered){
// 鼠标移入
// 绑定指针移动事件
document.body.addEventListener('pointermove',(event)=>{
const cursorPosition=getCursorPosition(event,rect);
// 更新坐标
updateElementPosition(cursorPosition.x,cursorPosition.y);
})
}else{
// 鼠标移出,初始化坐标
const numbers=updateNumbers();
updateElementPosition(numbers.number1 * 10,numbers.number2 * 10);
}
// 逐帧绘制
requestAnimationFrame(animationLoop);
}
animationLoop();
}
getNumbersFromDate();