# 手指缩小扩大

<img id="image" src="1.png">
1
var eleImg = document.querySelector('#image');
var store = {
    scale: 1
};
// 缩放事件的处理
eleImg.addEventListener('touchstart', function (event) {
    var touches = event.touches;
    var events = touches[0];
    var events2 = touches[1];

    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;
});
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
上次更新: 3/8/2023, 16:15:07