uniapp实现摇骰子
实现思路
在uniapp中实现摇骰子功能,主要通过CSS动画模拟骰子旋转效果,结合随机数生成骰子点数。关键点包括骰子3D旋转动画的触发、随机结果的生成以及动画结束后的回调处理。
骰子3D动画实现
通过CSS transform属性实现骰子的旋转动画效果,示例CSS代码:
.dice {
width: 100px;
height: 100px;
position: relative;
transform-style: preserve-3d;
transition: transform 1s ease-out;
}
.dice-face {
position: absolute;
width: 100%;
height: 100%;
background: white;
border: 2px solid #333;
border-radius: 10px;
display: flex;
justify-content: center;
align-items: center;
font-size: 24px;
}
随机点数生成
通过JavaScript的Math.random()生成1-6的随机数:
function rollDice() {
return Math.floor(Math.random() * 6) + 1;
}
完整组件示例
<template>
<view class="container">
<view
class="dice"
:style="{transform: diceRotation}"
@click="startRoll"
>
<view class="dice-face" v-for="n in 6" :key="n">
{{n}}
</view>
</view>
<view v-if="result" class="result">结果: {{result}}</view>
</view>
</template>
<script>
export default {
data() {
return {
isRolling: false,
result: null,
diceRotation: ''
}
},
methods: {
startRoll() {
if(this.isRolling) return;
this.isRolling = true;
this.result = null;
// 随机旋转角度
const xRot = Math.floor(Math.random() * 10) * 360;
const yRot = Math.floor(Math.random() * 10) * 360;
this.diceRotation = `rotateX(${xRot}deg) rotateY(${yRot}deg)`;
setTimeout(() => {
this.result = this.rollDice();
this.isRolling = false;
}, 1000);
},
rollDice() {
return Math.floor(Math.random() * 6) + 1;
}
}
}
</script>
优化方向
- 添加重力感应支持,通过uniapp的加速度计API实现真实摇动触发
- 增加音效反馈,在动画开始和结束时播放相应音效
- 美化骰子样式,使用圆点代替数字显示
- 添加多骰子同时掷出的功能
注意事项
- CSS 3D变换在某些低端设备上可能出现性能问题
- 动画持续时间应与随机数生成时机匹配
- 多次快速点击需做防抖处理
- 真机测试时注意各平台的兼容性差异







