uniapp 摇骰子
uniapp 摇骰子实现方法
页面布局
在 pages 目录下创建骰子页面(如 dice.vue),使用 view 和 image 组件构建骰子界面。骰子图片可通过静态资源或网络地址加载。

<template>
<view class="dice-container">
<image :src="diceImage" class="dice" @click="rollDice"></image>
<text class="result">当前点数: {{ currentValue }}</text>
</view>
</template>
骰子动画逻辑
通过 CSS 旋转动画模拟骰子摇晃效果,结合 JavaScript 随机数生成点数。
<script>
export default {
data() {
return {
diceImage: '/static/dice1.png', // 初始骰子图
currentValue: 1,
isRolling: false
}
},
methods: {
rollDice() {
if (this.isRolling) return;
this.isRolling = true;
// 动画持续时间(毫秒)
const duration = 1000;
const startTime = Date.now();
// 动画帧更新
const animate = () => {
const elapsed = Date.now() - startTime;
if (elapsed < duration) {
// 快速切换骰子图片产生旋转效果
const randomValue = Math.floor(Math.random() * 6) + 1;
this.diceImage = `/static/dice${randomValue}.png`;
requestAnimationFrame(animate);
} else {
// 动画结束,确定最终点数
const finalValue = Math.floor(Math.random() * 6) + 1;
this.currentValue = finalValue;
this.diceImage = `/static/dice${finalValue}.png`;
this.isRolling = false;
}
};
animate();
}
}
}
</script>
CSS 样式
添加骰子旋转动画和基本样式:
<style>
.dice-container {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
}
.dice {
width: 200rpx;
height: 200rpx;
transition: transform 0.2s;
}
.dice:active {
transform: rotate(180deg);
}
.result {
margin-top: 40rpx;
font-size: 32rpx;
}
</style>
优化建议
- 预加载图片:在
onLoad生命周期中预加载所有骰子图片,避免动画卡顿。 - 震动反馈:调用
uni.vibrate()增强交互体验。 - 音效:添加摇晃和停止音效。
- 3D 效果:使用 CSS 3D 变换实现更逼真的旋转。
完整资源准备
需准备 6 张骰子面图片(dice1.png 到 dice6.png),存放在 static 目录下。图片建议使用透明背景 PNG 格式,尺寸保持一致。







