uniapp 摇杆
uniapp 实现虚拟摇杆的方法
在 uniapp 中实现虚拟摇杆可以通过 canvas 绘制并结合触摸事件来完成。以下是一个基本的实现方案:
基础摇杆绘制
使用 canvas 在页面上绘制摇杆的基础样式。通常包括一个固定外圈和一个可移动的内圈。
<template>
<view>
<canvas canvas-id="joystickCanvas"
@touchstart="onTouchStart"
@touchmove="onTouchMove"
@touchend="onTouchEnd"
style="width: 200px; height: 200px;"></canvas>
</view>
</template>
初始化摇杆
在页面加载时初始化摇杆的位置和大小。

data() {
return {
centerX: 100,
centerY: 100,
outerRadius: 80,
innerRadius: 30,
innerX: 100,
innerY: 100
}
},
onReady() {
this.drawJoystick();
}
绘制摇杆函数
通过 canvas 绘制摇杆的视觉元素。
methods: {
drawJoystick() {
const ctx = uni.createCanvasContext('joystickCanvas', this);
// 绘制外圈
ctx.arc(this.centerX, this.centerY, this.outerRadius, 0, 2 * Math.PI);
ctx.setFillStyle('#CCCCCC');
ctx.fill();
// 绘制内圈
ctx.arc(this.innerX, this.innerY, this.innerRadius, 0, 2 * Math.PI);
ctx.setFillStyle('#666666');
ctx.fill();
ctx.draw();
}
}
处理触摸事件
实现触摸事件来控制摇杆移动。

onTouchStart(e) {
this.handleTouchMove(e);
},
onTouchMove(e) {
this.handleTouchMove(e);
},
onTouchEnd() {
// 松开后复位
this.innerX = this.centerX;
this.innerY = this.centerY;
this.drawJoystick();
},
handleTouchMove(e) {
const touch = e.touches[0];
const deltaX = touch.x - this.centerX;
const deltaY = touch.y - this.centerY;
const distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY);
// 限制摇杆在内圈移动
if (distance <= this.outerRadius) {
this.innerX = touch.x;
this.innerY = touch.y;
} else {
// 如果超出外圈,则按比例限制在内
const ratio = this.outerRadius / distance;
this.innerX = this.centerX + deltaX * ratio;
this.innerY = this.centerY + deltaY * ratio;
}
this.drawJoystick();
this.calculateDirection(deltaX, deltaY);
}
计算方向
根据摇杆偏移量计算方向或控制指令。
calculateDirection(deltaX, deltaY) {
const angle = Math.atan2(deltaY, deltaX) * 180 / Math.PI;
const distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY) / this.outerRadius;
// 根据角度判断方向
if (distance > 0.2) { // 设置一个最小触发阈值
if (angle >= -45 && angle < 45) {
console.log('向右');
} else if (angle >= 45 && angle < 135) {
console.log('向下');
} else if (angle >= -135 && angle < -45) {
console.log('向上');
} else {
console.log('向左');
}
}
}
性能优化
对于频繁的绘制操作,可以适当优化:
- 使用 requestAnimationFrame 进行绘制
- 减少不必要的重绘
- 对方向计算进行节流处理
扩展功能
可以根据需要扩展以下功能:
- 添加震动反馈
- 实现八方向控制
- 添加自定义样式选项
- 封装为可复用的组件
这个实现方案提供了基本的虚拟摇杆功能,可以根据具体需求进行调整和扩展。






