-
Notifications
You must be signed in to change notification settings - Fork 0
/
moveable.js
45 lines (40 loc) · 1.41 KB
/
moveable.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
export default class Moveable {
constructor(ele) {
this.moveTarget = ele;
this.lastX = undefined;
this.lastY = undefined;
if (getComputedStyle(ele).display === 'inline' && ['IMG', 'VIDEO'].indexOf(ele.tagName) === -1) {
throw 'Opps, is that target a transformable element?';
}
this._move = e => {
e.preventDefault();
this.lastX = this.lastX ?? e.clientX;
this.lastY = this.lastY ?? e.clientY;
let dx = e.clientX - this.lastX;
let dy = e.clientY - this.lastY;
let style = getComputedStyle(this.moveTarget);
if (style.transform === 'none') {
this.moveTarget.style.transform = `matrix(1,0,0,1,${dx},${dy})`;
} else {
let matrix = this.moveTarget.style.transform;
let matrixArr = matrix.replace('matrix(', '').replace(')', '').split(',');
matrixArr[4] = Number(matrixArr[4]) + dx;
matrixArr[5] = Number(matrixArr[5]) + dy;
this.moveTarget.style.transform = `matrix(${matrixArr.join()})`;
}
this.lastX = e.clientX;
this.lastY = e.clientY;
}
this._init();
}
_init() {
this.moveTarget.addEventListener('mousedown', e => {
window.addEventListener('mousemove', this._move, true);
}, true)
window.addEventListener('mouseup', e => {
window.removeEventListener('mousemove', this._move, true);
this.lastX = undefined;
this.lastY = undefined;
}, true)
}
}