使用Vue实现洗牌动画
使用CSS和Vue实现洗牌动画
洗牌动画可以通过CSS过渡和Vue的动态数据绑定实现。以下是实现步骤:
准备数据
data() {
return {
cards: [
{ id: 1, value: 'A', suit: '♥' },
{ id: 2, value: '2', suit: '♦' },
// 其他卡牌...
],
isShuffling: false
}
}
CSS样式
.card {
width: 80px;
height: 120px;
position: absolute;
transition: all 0.5s ease;
background: white;
border-radius: 5px;
display: flex;
justify-content: center;
align-items: center;
font-size: 24px;
box-shadow: 0 2px 5px rgba(0,0,0,0.2);
transform-origin: center;
}
洗牌方法
methods: {
shuffle() {
this.isShuffling = true;
// 随机打乱数组
for (let i = this.cards.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[this.cards[i], this.cards[j]] = [this.cards[j], this.cards[i]];
}
setTimeout(() => {
this.isShuffling = false;
}, 500);
}
}
模板部分
<div class="deck">
<div
v-for="(card, index) in cards"
:key="card.id"
class="card"
:style="{
left: `${index * 10}px`,
transform: isShuffling ?
`translate(${Math.random() * 100 - 50}px, ${Math.random() * 100 - 50}px) rotate(${Math.random() * 60 - 30}deg)` :
`translate(${index * 10}px, 0) rotate(0deg)`
}"
>
<span>{{ card.value }}</span>
<span>{{ card.suit }}</span>
</div>
</div>
<button @click="shuffle">洗牌</button>
使用GSAP实现更流畅的动画
如果需要更复杂的动画效果,可以使用GSAP库:
安装GSAP
npm install gsap
使用GSAP实现动画
import { gsap } from 'gsap';
methods: {
shuffleWithGSAP() {
const cards = this.$el.querySelectorAll('.card');
gsap.to(cards, {
duration: 0.5,
x: () => Math.random() * 200 - 100,
y: () => Math.random() * 200 - 100,
rotation: () => Math.random() * 360,
ease: "power2.out",
onComplete: () => {
// 重新排列卡牌
gsap.to(cards, {
duration: 0.5,
x: (i) => i * 10,
y: 0,
rotation: 0
});
}
});
// 同时打乱数据顺序
this.cards.sort(() => Math.random() - 0.5);
}
}
使用Vue Transition Group
Vue的TransitionGroup组件可以处理列表元素的进入/离开动画:
<transition-group name="shuffle" tag="div" class="deck">
<div
v-for="card in cards"
:key="card.id"
class="card"
>
{{ card.value }}{{ card.suit }}
</div>
</transition-group>
.shuffle-move {
transition: transform 0.5s;
}
添加3D效果
通过CSS 3D变换可以增强视觉效果:
.card {
transform-style: preserve-3d;
transition: transform 0.5s;
}
.card:hover {
transform: rotateY(180deg);
}
以上方法可以根据需求组合使用,CSS过渡适合简单动画,GSAP适合复杂动画,TransitionGroup适合列表重排动画。






