-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdraggable.js
422 lines (369 loc) · 11.6 KB
/
draggable.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
// you don't need to edit this file, but you can look through it to see how the draggable works!
// -Max
let dragStartCallback = function (element, x, y, scale, rotation) {
// the default drag callback does nothing
};
let dragMoveCallback = function (element, x, y, scale, rotation) {
// the default drag callback does nothing
};
let dragEndCallback = function (element, x, y, scale, rotation) {
// the default drag callback does nothing
};
function setDragStartCallback(callback) {
if (typeof callback === "function") {
dragStartCallback = callback;
} else {
throw new Error("drag callback must be a function!");
}
}
function setDragMoveCallback(callback) {
if (typeof callback === "function") {
dragMoveCallback = callback;
} else {
throw new Error("drag callback must be a function!");
}
}
function setDragEndCallback(callback) {
if (typeof callback === "function") {
dragEndCallback = callback;
} else {
throw new Error("drag callback must be a function!");
}
}
let activeElement = null;
let mousedown = false;
let handle_state = false;
let offset_x;
let offset_y;
window.last_z = 1;
let initialDistance;
let initialScale;
let initialWidth;
let initialHeight;
let initialAngle;
let resizeHandle = document.createElement("div");
let handleContainer = document.createElement("div");
resizeHandle.classList.add("resize-handle");
handleContainer.classList.add("handle-container");
handleContainer.appendChild(resizeHandle);
document.body.appendChild(handleContainer);
var isTouchDevice = "ontouchstart" in document.documentElement;
// this moves the outline rectangle to match the current element
function updateHandleContainer() {
if (!activeElement) {
handleContainer.style.left = "-1000px";
return;
}
let styles = window.getComputedStyle(activeElement);
let scale = getCurrentScale(activeElement);
let rotate = getCurrentRotation(activeElement);
handleContainer.style.left = styles.left;
handleContainer.style.top = styles.top;
handleContainer.style.width = parseFloat(styles.width) * scale + "px";
handleContainer.style.height = parseFloat(styles.height) * scale + "px";
handleContainer.style.transform = `
translate(-50%,-50%)
rotate(${rotate * (180 / Math.PI)}deg)`;
}
// Add this at the start of the file, after other variable declarations
let maxZIndex = 1;
const DRAG_Z_INDEX = 100000;
function startAction(ev, isMouse) {
let touches = Array.from(ev.touches);
let firstTouch = touches[0];
if (firstTouch.target.classList.contains("resize-handle")) {
ev.preventDefault();
initialScale = getCurrentScale(activeElement);
initialAngle = getCurrentRotation(activeElement);
let styles = window.getComputedStyle(activeElement);
dragStartCallback(
activeElement,
parseFloat(styles.left),
parseFloat(styles.top),
initialScale,
initialAngle
);
}
if (firstTouch.target.classList.contains("draggable")) {
if (firstTouch.target.tagName === "IMG") {
ev.preventDefault();
}
let selectedElement = checkImageCoord(firstTouch.target, ev);
if (!selectedElement || !selectedElement.classList.contains("draggable")) {
return;
}
activeElement = selectedElement;
let bounds = selectedElement.getBoundingClientRect();
if (isMouse) {
updateHandleContainer();
}
offset_x = firstTouch.clientX - bounds.left;
offset_y = firstTouch.clientY - bounds.top;
// Set extremely high z-index during drag
activeElement.style.zIndex = DRAG_Z_INDEX;
initialWidth = bounds.width;
initialHeight = bounds.height;
initialScale = getCurrentScale(activeElement);
initialAngle = getCurrentRotation(activeElement);
let secondTouch = touches[1];
if (secondTouch) {
let p1 = { x: firstTouch.clientX, y: firstTouch.clientY };
let p2 = { x: secondTouch.clientX, y: secondTouch.clientY };
let pDifference = sub(p1, p2);
let pMid = add(p1, scale(pDifference, 0.5));
initialDistance = distance(p1, p2);
initialAngle = angle(pDifference) - getCurrentRotation(selectedElement);
offset_x = pMid.x - bounds.left;
offset_y = pMid.y - bounds.top;
}
let styles = window.getComputedStyle(activeElement);
dragStartCallback(
activeElement,
parseFloat(styles.left),
parseFloat(styles.top),
initialScale,
initialAngle
);
}
}
document.body.addEventListener("touchstart", function (ev) {
if (activeElement) {
handleContainer.style.left = "-1000px";
}
startAction(ev, false);
});
document.body.addEventListener("mousedown", function (ev) {
if (isTouchDevice) {
return;
}
if (ev.target.classList.contains("resize-handle") && activeElement) {
let styles = window.getComputedStyle(activeElement);
let scale = getCurrentScale(activeElement);
let rotate = getCurrentRotation(activeElement);
let size = {
x: parseFloat(styles.width) * scale,
y: parseFloat(styles.height) * scale
};
handleContainer.style.transform = `
translate(-50%,-50%)
rotate(${rotate * (180 / Math.PI)}deg)`;
initialDistance = magnitude(size);
handle_state = "resize";
} else {
handle_state = false;
if (activeElement) {
handleContainer.style.left = "-1000px";
activeElement = false;
}
}
mousedown = true;
ev.touches = [ev];
startAction(ev, true);
});
document.body.addEventListener("touchend", function (ev) {
if (activeElement) {
handleContainer.style.left = "-1000px";
// Set to next available z-index when drag ends
maxZIndex++;
activeElement.style.zIndex = maxZIndex;
let styles = window.getComputedStyle(activeElement);
dragEndCallback(
activeElement,
parseFloat(styles.left),
parseFloat(styles.top),
getCurrentScale(activeElement),
getCurrentRotation(activeElement)
);
}
activeElement = null;
});
document.body.addEventListener("mouseup", function (ev) {
mousedown = false;
handle_state = false;
if (!activeElement) return;
// Set to next available z-index when drag ends
maxZIndex++;
activeElement.style.zIndex = maxZIndex;
initialScale = getCurrentScale(activeElement);
initialAngle = getCurrentRotation(activeElement);
let styles = window.getComputedStyle(activeElement);
dragEndCallback(
activeElement,
parseFloat(styles.left),
parseFloat(styles.top),
getCurrentScale(activeElement),
getCurrentRotation(activeElement)
);
});
function moveAction(ev, isMouse) {
if (!activeElement) {
return;
}
let touches = Array.from(ev.touches);
let firstTouch = touches[0];
let x = firstTouch.clientX - offset_x + initialWidth / 2;
let y = firstTouch.clientY - offset_y + initialHeight / 2;
let newScale = initialScale;
let newAngle = initialAngle;
let secondTouch = touches[1];
if (secondTouch) {
let p1 = { x: firstTouch.clientX, y: firstTouch.clientY };
let p2 = { x: secondTouch.clientX, y: secondTouch.clientY };
let pDifference = sub(p1, p2);
let pMid = add(p1, scale(pDifference, 0.5));
let newDistance = distance(p1, p2);
newAngle = angle(pDifference) - initialAngle;
newScale = initialScale * (newDistance / initialDistance);
x = pMid.x - offset_x + initialWidth / 2;
y = pMid.y - offset_y + initialHeight / 2;
}
if (handle_state === "resize") {
let b = activeElement.getBoundingClientRect();
let p1 = { x: firstTouch.clientX, y: firstTouch.clientY };
let center = { x: b.left + b.width / 2, y: b.top + b.height / 2 };
let p2 = add(center, sub(p1, center));
let newDistance = distance(p1, p2);
newScale = initialScale * (newDistance / initialDistance);
let pDifference = sub(p1, p2);
let handleAngle = angle(pDifference);
let styles = window.getComputedStyle(activeElement);
let w = parseFloat(styles.width);
let h = parseFloat(styles.height);
let a = Math.atan2(h, w) + Math.PI;
newAngle = handleAngle - a;
} else if (!handle_state) {
activeElement.style.left = x + "px";
activeElement.style.top = y + "px";
}
activeElement.style.transform = `
translate(-50%,-50%)
scale(${newScale})
rotate(${newAngle * (180 / Math.PI)}deg)`;
dragMoveCallback(activeElement, x, y, newScale, newAngle);
if (isMouse) {
try {
updateHandleContainer();
} catch (e) {
console.log(e);
}
}
}
document.body.addEventListener("mousemove", function (ev) {
ev.touches = [ev];
if (mousedown) {
moveAction(ev, true);
}
});
document.body.addEventListener(
"touchmove",
function (ev) {
ev.preventDefault();
moveAction(ev);
},
{ passive: false }
);
let canvas = document.createElement("canvas");
let ctx = canvas.getContext("2d");
// document.body.appendChild(ctx.canvas); // used for debugging
// this function checks if a pixel location in an image is opaque
// if it's not, it attemps to find the next image below it until
// it finds one
function checkImageCoord(img_element, event) {
// non-image elements are always considered opaque
if (img_element.tagName !== "IMG") {
return img_element;
}
img_element.crossOrigin = "anonymous";
let touches = Array.from(event.touches);
let firstTouch = touches[0];
// Get click coordinates
let x = firstTouch.clientX;
let y = firstTouch.clientY;
let w = (ctx.canvas.width = window.innerWidth);
let h = (ctx.canvas.height = window.innerHeight);
ctx.clearRect(0, 0, w, h);
let scale = getCurrentScale(img_element);
let rotation = getCurrentRotation(img_element);
let styles = window.getComputedStyle(img_element);
ctx.translate(parseFloat(styles.left), parseFloat(styles.top));
ctx.scale(scale, scale);
ctx.rotate(rotation);
ctx.drawImage(
img_element,
-img_element.width / 2,
-img_element.height / 2,
img_element.width,
img_element.height
);
ctx.resetTransform();
let alpha = 1;
try {
alpha = ctx.getImageData(x, y, 1, 1).data[3]; // [0]R [1]G [2]B [3]A
if (!img_element.complete) {
alpha = 1;
}
} catch (e) {
console.warn(`add crossorigin="anonymous" to your img`);
}
// If pixel is transparent, then retrieve the element underneath
// and trigger it's click event
if (alpha === 0) {
img_element.style.pointerEvents = "none";
let nextTarget = document.elementFromPoint(
firstTouch.clientX,
firstTouch.clientY
);
let nextEl = null;
if (nextTarget.classList.contains("draggable")) {
nextEl = checkImageCoord(nextTarget, event);
}
img_element.style.pointerEvents = "auto";
return nextEl;
} else {
//image is opaque at location
return img_element;
}
}
function getTransform(el) {
try {
let st = window.getComputedStyle(el, null);
let tr =
st.getPropertyValue("-webkit-transform") ||
st.getPropertyValue("-moz-transform") ||
st.getPropertyValue("-ms-transform") ||
st.getPropertyValue("-o-transform") ||
st.getPropertyValue("transform") ||
"FAIL";
return tr.split("(")[1].split(")")[0].split(",");
} catch (e) {
console.log(e);
return [0, 0, 0, 0];
}
}
function getCurrentScale(el) {
let values = getTransform(el);
return Math.sqrt(values[0] * values[0] + values[1] * values[1]);
}
function getCurrentRotation(el) {
let values = getTransform(el);
return Math.atan2(values[1], values[0]);
}
function add(a, b) {
return { x: a.x + b.x, y: a.y + b.y };
}
function sub(a, b) {
return { x: b.x - a.x, y: b.y - a.y };
}
function scale(a, s) {
return { x: a.x * s, y: a.y * s };
}
function magnitude(a) {
return Math.sqrt(Math.pow(a.x, 2) + Math.pow(a.y, 2));
}
function angle(b) {
return Math.atan2(b.y, b.x); //radians
}
function distance(a, b) {
return magnitude(sub(a, b));
}
export { setDragStartCallback, setDragMoveCallback, setDragEndCallback };