uniapp实现摇骰子
实现摇骰子的基本思路
通过随机数生成骰子点数,结合动画效果模拟摇骰子的过程,最终显示结果。
页面结构与样式
在 pages 目录下新建页面(如 dice),模板部分添加骰子容器和按钮:

<template>
<view class="container">
<view class="dice" :class="{'shake': isShaking}">{{ diceValue }}</view>
<button @click="rollDice">摇骰子</button>
</view>
</template>
<style>
.dice {
width: 100px;
height: 100px;
border: 2px solid #333;
border-radius: 10px;
display: flex;
justify-content: center;
align-items: center;
font-size: 40px;
margin: 50px auto;
}
.shake {
animation: shake 0.5s;
}
@keyframes shake {
0% { transform: rotate(0deg); }
25% { transform: rotate(-10deg); }
50% { transform: rotate(10deg); }
75% { transform: rotate(-10deg); }
100% { transform: rotate(0deg); }
}
</style>
逻辑实现
在 script 部分定义数据和方法:

export default {
data() {
return {
diceValue: 1,
isShaking: false
};
},
methods: {
rollDice() {
this.isShaking = true;
setTimeout(() => {
this.diceValue = Math.floor(Math.random() * 6) + 1;
this.isShaking = false;
}, 500);
}
}
};
优化方向
- 动画增强:使用 CSS 或
uni.createAnimation实现更复杂的动画效果。 - 音效:通过
uni.innerAudioContext添加摇骰子音效。 - 多骰子:扩展为多个骰子,通过数组管理点数。
多骰子实现示例
修改数据和方法:
data() {
return {
diceValues: [1, 1],
isShaking: false
};
},
methods: {
rollDice() {
this.isShaking = true;
setTimeout(() => {
this.diceValues = this.diceValues.map(() => Math.floor(Math.random() * 6) + 1);
this.isShaking = false;
}, 500);
}
}
模板调整为遍历 diceValues 显示多个骰子。
注意事项
- 动画时间需与随机数生成时机匹配,避免动画未结束就显示结果。
- 真机调试时部分 CSS 动画可能需加厂商前缀(如
-webkit-)。






