当前位置:首页 > uni-app

uniapp 摇骰子

2026-03-04 21:35:08uni-app

实现摇骰子功能的方法

使用动画和随机数生成骰子点数

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骰子组件:

uniapp 摇骰子

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命名空间下调用原生震动反馈:

uniapp 摇骰子

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渲染和网络功能。

标签: 骰子uniapp
分享给朋友:

相关文章

uniapp部署到服务器

uniapp部署到服务器

部署准备 确保本地开发环境已完成项目构建,生成静态文件(H5端为/dist/build/h5目录)。检查服务器环境是否安装Nginx/Apache等Web服务软件,并配置好域名解析。 上传文件 通…

uniapp发布到应用商店

uniapp发布到应用商店

发布到苹果App Store 确保开发者账号已注册并加入Apple Developer Program,年费99美元。在Xcode中生成iOS发布证书(.p12)和描述文件(Provisioning…

uniapp支付功能怎么实现

uniapp支付功能怎么实现

uniapp支付功能实现方法 准备工作 注册微信支付、支付宝等平台的开发者账号,获取必要的商户ID(mch_id)、API密钥(key)、应用ID(appid)等信息。确保项目已配置好相关支付SDK。…

uniapp开发电视应用

uniapp开发电视应用

开发环境准备 确保已安装HBuilderX最新版本,这是uniapp官方推荐的开发工具。安装Node.js环境,用于依赖管理和打包构建。准备Android Studio或Xcode用于调试和打包TV应…

uniapp视频

uniapp视频

uniapp视频开发基础 uniapp支持通过video组件实现视频播放功能,该组件兼容多端(H5、小程序、App等),基本用法如下: <template> <video…

uniapp如何赋值

uniapp如何赋值

uniapp 赋值方法 在 uniapp 中,赋值操作可以通过多种方式实现,具体取决于数据类型和场景。 数据绑定赋值 在模板中使用 {{}} 进行数据绑定,通过修改 data 中的值实现动态更…