前言
最近对 requestAnimationFrame 有点感兴趣。
正文
先贴个效果图:
再贴个代码:
'use client';
import { useEffect, useRef, useState } from 'react';
import styles from './styles.module.css';
export default function Effect() {
const position = useRef({ x: 0, y: 50 });
const done = useRef(false);
const [background, setBackgrond] = useState('');
function move() {
const { x, y } = position.current;
setBackgrond(
`radial-gradient(20% 40% at ${x}% ${y}%, red 0%, transparent 100%)`
);
if (x >= 0 && x < 50 && y <= 50 && y > 0) {
position.current.x++;
position.current.y--;
} else if (x >= 50 && x < 100 && y >= 0 && y < 50) {
position.current.x++;
position.current.y++;
} else if (x <= 100 && x > 50 && y >= 50 && y < 100) {
position.current.x--;
position.current.y++;
} else if (x <= 50 && x > 0 && y <= 100 && y > 50) {
position.current.x--;
position.current.y--;
}
if (!done.current) requestAnimationFrame(move);
}
useEffect(() => {
requestAnimationFrame(move);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return (
<div className={styles.button}>
<button>CLICK</button>
<span style={{ background }}></span>
</div>
);
}
.button {
position: relative;
display: block;
margin: 50px;
padding: 2px;
width: 107px;
height: 44px;
text-align: center;
background: #ccc3;
border-radius: 20px;
overflow: hidden;
}
.button button {
width: 100%;
height: 100%;
background: white;
border-radius: 20px;
}
.button span {
content: '';
position: absolute;
z-index: -1;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
ps:若有错误之处,烦请留言指正。