帮我写个 手势摇杆html 脚本
时间: 2023-09-10 16:15:33 浏览: 41
好的,以下是一个简单的手势摇杆的 HTML 和 JavaScript 代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>手势摇杆</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style type="text/css">
/* 设置摇杆的样式 */
#joystick {
width: 100px;
height: 100px;
border-radius: 50%;
background-color: #ccc;
position: relative;
}
#stick {
width: 50px;
height: 50px;
border-radius: 50%;
background-color: #333;
position: absolute;
top: 25px;
left: 25px;
}
</style>
</head>
<body>
<div id="joystick">
<div id="stick"></div>
</div>
<script type="text/javascript">
// 获取摇杆元素
var joystick = document.getElementById('joystick');
var stick = document.getElementById('stick');
// 初始化手势变量
var startX = 0, startY = 0, endX = 0, endY = 0, deltaX = 0, deltaY = 0;
// 添加触摸事件监听器
joystick.addEventListener('touchstart', function(event) {
// 阻止默认的滚动行为
event.preventDefault();
// 获取触摸点的位置
startX = event.touches[0].pageX;
startY = event.touches[0].pageY;
}, false);
joystick.addEventListener('touchmove', function(event) {
// 阻止默认的滚动行为
event.preventDefault();
// 获取触摸点的位置
endX = event.touches[0].pageX;
endY = event.touches[0].pageY;
// 计算手指移动的距离
deltaX = endX - startX;
deltaY = startY - endY; // 注意这里要反过来,因为 Y 轴的正方向是向下的
// 限制手势的范围在摇杆范围内
var distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY);
if (distance > 50) {
var ratio = 50 / distance;
deltaX *= ratio;
deltaY *= ratio;
}
// 移动摇杆的位置
stick.style.left = (50 + deltaX) + 'px';
stick.style.top = (50 - deltaY) + 'px'; // 注意这里也要反过来
}, false);
joystick.addEventListener('touchend', function(event) {
// 阻止默认的滚动行为
event.preventDefault();
// 摇杆回到中心位置
stick.style.left = '50px';
stick.style.top = '50px';
}, false);
</script>
</body>
</html>
```
这段代码实现了一个简单的手势摇杆,用户可以在摇杆范围内拖动小球来控制方向,代码中添加了触摸事件监听器,通过计算手指移动的距离来移动小球的位置。需要注意的是,由于移动设备屏幕大小不一,因此这里使用了 `viewport` 标签来自适应屏幕大小。