-
Notifications
You must be signed in to change notification settings - Fork 0
/
touch.html
106 lines (93 loc) · 2.33 KB
/
touch.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>双指缩放</title>
</head>
<body>
<img id="img" src="https://dss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=2647819114,3999828491&fm=26&gp=0.jpg" />
</body>
<script>
var eleImg = document.querySelector('#img');
var store = {
scale: 1
};
// 缩放事件的处理
eleImg.addEventListener('touchstart', function (event) {
var touches = event.touches;
var events = touches[0];
var events2 = touches[1];
console.log(event,events,events2)
event.preventDefault();
// 第一个触摸点的坐标
store.pageX = events.pageX;
store.pageY = events.pageY;
store.moveable = true;
if (events2) {
store.pageX2 = events2.pageX;
store.pageY2 = events2.pageY;
}
store.originScale = store.scale || 1;
});
document.addEventListener('touchmove', function (event) {
if (!store.moveable) {
return;
}
event.preventDefault();
var touches = event.touches;
var events = touches[0];
var events2 = touches[1];
// 双指移动
if (events2) {
// 第2个指头坐标在touchmove时候获取
if (!store.pageX2) {
store.pageX2 = events2.pageX;
}
if (!store.pageY2) {
store.pageY2 = events2.pageY;
}
// 获取坐标之间的举例
var getDistance = function (start, stop) {
return Math.hypot(stop.x - start.x, stop.y - start.y);
};
// 双指缩放比例计算
var zoom = getDistance({
x: events.pageX,
y: events.pageY
}, {
x: events2.pageX,
y: events2.pageY
}) /
getDistance({
x: store.pageX,
y: store.pageY
}, {
x: store.pageX2,
y: store.pageY2
});
// 应用在元素上的缩放比例
var newScale = store.originScale * zoom;
// 最大缩放比例限制
if (newScale > 3) {
newScale = 3;
}
// 记住使用的缩放值
store.scale = newScale;
// 图像应用缩放效果
eleImg.style.transform = 'scale(' + newScale + ')';
}
});
document.addEventListener('touchend', function () {
store.moveable = false;
delete store.pageX2;
delete store.pageY2;
});
document.addEventListener('touchcancel', function () {
store.moveable = false;
delete store.pageX2;
delete store.pageY2;
});
</script>
</html>