场景
React+css 实现老虎机滚筒动画效果
核心
核心在于,useRef
、transition
、transform
,ref操作dome 控制背景transform 向下移动,添加动画的平滑过度
效果图
操作
1.滚动图片(自定义)
2、结构
开始/暂停
const rollersRef = useRef([]);
//开始/暂停
const [isAnimating, setIsAnimating] = useState(false);
// 开始/停止动画
useEffect(() => {
let interval;
if (isAnimating) {
resetRollers(); // 立即执行一次
interval = setInterval(() => resetRollers(), 500);
}
//isAnimating为false时清除定时滚动 clearInterval
return () => {
clearInterval(interval);
};
}, [isAnimating]);
//滚动控制,初始为回到原位
const resetRollers = () => {
//初始无动画 位置为0
rollersRef.current.style.transition = "none";
rollersRef.current.style.transform = `translateY(${0}px)`;
//时间戳 10后 感动到-2000位置
setTimeout(() => {
//滚动的效果,添加2S 动画过渡
rollersRef.current.style.transition = `transform ${2}s cubic-bezier(0.17, 0.84, 0.44, 1)`;
rollersRef.current.style.transform = `translateY(-${2000}px)`;
}, 10);//与上面的循环执行相对于
}
div
<div className="image-roller">
<div
className="image-list"
ref={rollersRef}
>
//可以固定也可以动态
<div className="ywbg"></div>
<div className="ywbg"></div>
<div className="ywbg"></div>
<div className="ywbg"></div>
<div className="ywbg"></div>
<div className="ywbg"></div>
<div className="ywbg"></div>
<div className="ywbg"></div>
</div>
</div>
<div>
<button className={`btn ${isAnimating ? "btn-stop" : "btn-start"}`}
onClick={() => setIsAnimating(!isAnimating)} >
{isAnimating ? "停止滚动" : "开始滚动"}
</button>
</div>
css
.image-roller {
position: relative;
width: 200px;
height: 100px;
background: linear-gradient(to bottom, #444, #222);
border-radius: 8px;
color: white;
font-size: 40px;
font-weight: bold;
text-align: center;
line-height: 100px;
overflow: hidden;
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
display: inline-block;
margin: 5px;
}
.image-list {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
// transition: transform 2s cubic-bezier(0.17, 0.84, 0.44, 1);
}
.ywbg {
background: url(${YW}) no-repeat; //固定背景图,也可以动态赋值
background-size: 100% 100%;
width: 100%;
height: 100%;
}
images: [
"😀","🍎","🐶","🚗",
"😃","🍐","🐱","🚕",
"😄","🍊","🐭","🚙",
"😁","🍋","🐹","🚌",
"😆","🍌","🐰","🚎",
"😅","🍉","🦊","🏎",
"😂","🍇","🐻","🚓",
"🤣","🍓","🐼","🚑",
"😊","🍈","🐨","🚒",
"😇","🍒","🐯","🚐",
"🙂","🍑","🦁","🚚",
"🙃","🥭","🐮","🚛",
"😉","🍍","🐷","🚜",
"😌","🥥","🐸","🛴",
"😍","🥝","🐵","🚲",
"🥰","🍅","🐔","🛵",
],