-
-
Notifications
You must be signed in to change notification settings - Fork 43
/
Copy pathapp.js
89 lines (75 loc) · 2.33 KB
/
app.js
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
import { compose, translate, scale, toCSS, fromOneMovingPoint, fromTwoMovingPoints } from 'transformation-matrix'
if (document.readyState !== 'loading') {
setTimeout(startup, 0)
} else {
document.addEventListener('DOMContentLoaded', startup)
}
function startup () {
const initialMatrix = compose([
translate(40, 150),
scale(0.5, 0.5, 0, 0)
])
let curState = {
startingPoints: [],
matrix: initialMatrix
}
const el = document.getElementById('draggable-item')
el.addEventListener('touchstart', onTouchEvent)
el.addEventListener('touchmove', onTouchEvent)
el.addEventListener('touchend', onTouchEvent)
el.addEventListener('touchcancel', onTouchEvent)
el.addEventListener('wheel', e => e.preventDefault(), { passive: false }) // prevent zoom
el.oncontextmenu = function () { return false } // prevents android context menu
setState(curState) // init
console.log('ready')
// Set next state and syncs objects
function setState (nextState) {
curState = nextState
el.style.transformOrigin = '0 0'
el.style.transform = toCSS(nextState.matrix)
}
// handle gestures
function onTouchEvent (evt) {
const coords = []
for (const touch of evt.touches) {
coords.push({ x: touch.clientX, y: touch.clientY })
}
console.log(evt.type, JSON.stringify(coords))
switch (evt.type) {
// onTouchStart, onTouchEnd
case 'touchstart':
case 'touchend':
setState({
startingPoints: coords.length <= 2 ? coords : [],
matrix: curState.matrix
})
break
// onTouchMove
case 'touchmove': {
if (coords.length < 1 || coords.length > 2) return
const additionalMatrix = coords.length === 1
? fromOneMovingPoint(curState.startingPoints[0], coords[0])
: fromTwoMovingPoints(curState.startingPoints[0], curState.startingPoints[1], coords[0], coords[1])
const nextMatrix = compose(
additionalMatrix,
curState.matrix
)
setState({
startingPoints: coords,
matrix: nextMatrix
})
break
}
// onTouchCancel
case 'touchcancel':
setState({
startingPoints: [],
matrix: initialMatrix
})
break
// default
default:
throw new Error('Unhandled event')
}
}
}