uniapp 摇骰子
实现摇骰子功能的方法
使用动画和随机数生成骰子点数
在pages/index/index.vue中创建骰子组件,通过CSS动画模拟摇晃效果。利用Math.random()生成1-6的随机数,动画结束后显示最终点数。
<template>
<view class="container">
<view
class="dice"
:class="{ 'shake': isShaking }"
@click="rollDice"
>
{{ currentValue }}
</view>
</view>
</template>
<script>
export default {
data() {
return {
isShaking: false,
currentValue: 1
}
},
methods: {
rollDice() {
if (this.isShaking) return;
this.isShaking = true;
this.currentValue = '...';
setTimeout(() => {
this.currentValue = Math.floor(Math.random() * 6) + 1;
this.isShaking = false;
}, 1000);
}
}
}
</script>
<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;
background-color: #fff;
}
.shake {
animation: shake 0.5s cubic-bezier(.36,.07,.19,.97) both;
}
@keyframes shake {
0% { transform: translateX(0) }
25% { transform: translateX(-10px) }
50% { transform: translateX(10px) }
75% { transform: translateX(-10px) }
100% { transform: translateX(0) }
}
</style>
使用3D骰子模型增强视觉效果
通过three.js或现成的3D骰子组件实现更真实的3D效果。需先安装相关依赖:
npm install three @types/three
创建3D骰子组件:

import * as THREE from 'three';
// 在mounted中初始化3D场景
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, width/height, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
// 创建骰子几何体
const geometry = new THREE.BoxGeometry(1, 1, 1);
const material = new THREE.MeshBasicMaterial({ color: 0xffffff });
const dice = new THREE.Mesh(geometry, material);
scene.add(dice);
// 添加动画循环
function animate() {
requestAnimationFrame(animate);
dice.rotation.x += 0.01;
dice.rotation.y += 0.01;
renderer.render(scene, camera);
}
animate();
多平台适配注意事项
微信小程序特殊处理
在manifest.json中配置"mp-weixin"的usingComponents,如需使用webGL需开启相关权限。
APP端优化
考虑使用原生动画API提升性能,在plus命名空间下调用原生震动反馈:

plus.device.vibrate(200);
H5端兼容性 CSS动画需添加各浏览器前缀,3D效果需检测WebGL支持情况:
const isWebGLAvailable = () => {
try {
const canvas = document.createElement('canvas');
return !!window.WebGLRenderingContext &&
(canvas.getContext('webgl') || canvas.getContext('experimental-webgl'));
} catch(e) {
return false;
}
}
扩展功能实现
多人联机骰子
通过uni.connectSocket实现WebSocket通信,同步各方骰子结果:
const socketTask = uni.connectSocket({
url: 'wss://your.server.url',
success: () => {
socketTask.onMessage(res => {
console.log('收到服务器消息:', res.data)
});
}
});
历史记录存储
使用uni.setStorage保存每次投掷记录:
const history = uni.getStorageSync('diceHistory') || [];
history.push({
value: this.currentValue,
time: new Date().toLocaleString()
});
uni.setStorageSync('diceHistory', history);
性能优化建议
- 避免频繁的DOM操作,使用CSS硬件加速
- 3D场景中合理设置
renderer.setPixelRatio匹配设备DPI - 小程序端使用
<canvas>代替DOM实现动画 - 预加载骰子纹理等资源,减少延迟
以上方案可根据具体需求组合使用,基础版本使用CSS动画即可满足大多数场景,需要更复杂效果时可逐步引入3D渲染和网络功能。






