摇杆+页面手势的 html 脚本
时间: 2023-08-16 08:06:30 浏览: 54
好的,以下是一个同时支持手势和摇杆的 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);
// 添加页面手势监听器
document.addEventListener('gesturestart', function(event) {
// 阻止默认的滚动行为
event.preventDefault();
}, false);
document.addEventListener('gesturechange', function(event) {
// 阻止默认的滚动行为
event.preventDefault();
// 获取手势缩放比例
var scale = event.scale;
// 缩放摇杆的大小
joystick.style.width = (100 * scale) + 'px';
joystick.style.height = (100 * scale) + 'px';
stick.style.width = (50 * scale) + 'px';
stick.style.height = (50 * scale) + 'px';
// 限制摇杆的最小大小
if (joystick.offsetWidth < 50) {
joystick.style.width = '50px';
joystick.style.height = '50px';
stick.style.width = '25px';
stick.style.height = '25px';
}
// 限制摇杆的最大大小
if (joystick.offsetWidth > window.innerWidth / 2) {
joystick.style.width = (window.innerWidth / 2) + 'px';
joystick.style.height = (window.innerWidth / 2) + 'px';
stick.style.width = (window.innerWidth / 4) + 'px';
stick.style.height = (window.innerWidth / 4) + 'px';
}
}, false);
document.addEventListener('gestureend', function(event) {
// 阻止默认的滚动行为
event.preventDefault();
}, false);
</script>
</body>
</html>
```
这段代码实现了一个同时支持手势和摇杆的控制方式,用户可以通过拖动摇杆来控制方向,也可以通过手势缩放来调整摇杆的大小,代码中添加了触摸事件监听器和页面手势监听器,通过计算手指移动的距离来移动小球的位置,通过手势缩放来调整摇杆的大小。需要注意的是,由于移动设备屏幕大小不一,因此这里使用了 `viewport` 标签来自适应屏幕大小。