-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcrop.js
566 lines (437 loc) · 16.3 KB
/
crop.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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
function Crop(canvasLiveSelector, options){
// short functionality description
// (image) -> (canvas) -> covert to data -> image -> (canvas with size of a crop) -> covert to data
// -> callback(data || crop details with url)
// temp logging fn
var log = console.log.bind(console);
if ( typeof canvasLiveSelector === 'undefined') {
throw new Error('cannot init the crop module wotthout preset canvas selector');
}
// necessary values
var canvasLive = document.querySelectorAll(canvasLiveSelector)[0],
ctxLive = canvasLive.getContext('2d'),
// temp hidden canvas
canvasCropped = document.createElement('canvas'),
ctxCropped = canvasCropped.getContext('2d'),
dragging = false, // dragging event flag
tainted = false, // we may not need it
imgSource = new Image(),
imgToCrop = new Image(),
outputFormat = 'image/jpeg',
outputQuality = 1;
// optional values
var inpSrcTrigger, inpSrcTriggerEvent, // selectors for url trigger
cropTrigger, cropTriggerEvent,
inpSrc, // url image input
inpFile; // file image input
// selection canvas sizes and predefined properties
var sel = {
x: undefined,
y: undefined,
w: undefined,
h: undefined,
lineColor: '#fff',
lineWidth: 2,
squareSize: 12,
startDragShiftX: undefined,
startDragShiftY: undefined,
};
// source canvas sizes
var source = {
x: undefined,
y: undefined,
w: undefined,
h: undefined,
};
// core events initalisation
(function init(){
/******************************************************************
* EVENT LIST
******************************************************************/
// window events
window.addEventListener('load', function() {
resizeCanvasToParentEl(ctxLive, canvasLive);
});
window.addEventListener('resize', function() {
resizeCanvasToParentEl(ctxLive, canvasLive);
calculateSourceImagePos(imgSource, ctxLive, canvasLive);
resetSelectionToDefault(canvasLive);
drawCanvasLive();
});
// draw image if loaded
imgSource.addEventListener('load', function() {
calculateSourceImagePos(imgSource, ctxLive, canvasLive);
resetSelectionToDefault(canvasLive);
drawCanvasLive();
});
// imgSource.addEventListener('error', function(e) {
// log(e);
// });
// EDITING EVENTS
// click
canvasLive.addEventListener('click', function(e) {
saveMouseCoordinates(e, canvasLive);
drawCanvasLive();
});
// pseudo-dragging events
canvasLive.addEventListener('mousedown', function(e) {
dragging = true;
saveDragShiftValues(e, canvasLive);
});
canvasLive.addEventListener('mousemove', function(e) {
if (dragging) {
saveMouseCoordinates(e, canvasLive);
drawCanvasLive();
}
});
canvasLive.addEventListener('mouseup', function() {
dragging = false;
});
canvasLive.addEventListener('mouseleave', function() {
dragging = false;
});
// pseudo-dragging mobile events
canvasLive.addEventListener('touchstart', function(e) {
dragging = true;
saveDragShiftValues(e, canvasLive);
});
canvasLive.addEventListener('touchmove', function(e) {
if (dragging) {
saveMouseCoordinates(e, canvasLive);
drawCanvasLive();
}
});
canvasLive.addEventListener('touchend', function() {
dragging = false;
});
canvasLive.addEventListener('touchcancel', function() {
dragging = false;
});
})();
/******************************************************************
* API FUNCTIONS
******************************************************************/
// init file input
function setImageSourceFileInput(inpFileSelector, successCallback) {
inpFile = document.querySelectorAll(inpFileSelector)[0];
//initalise
inpFile.addEventListener('change', function() {
var imageSourceFile = new FileReader();
imageSourceFile.addEventListener('loadend', function() {
imgSource.src = imageSourceFile.result;
});
if (inpFile.files[0]) {
imageSourceFile.readAsDataURL(inpFile.files[0]);
successCallback();
}
});
}
//
function setImageSourceUrlInput(inpSrcSelector, inpSrcTriggerSelector, inpSrcTriggerEventVal) {
if ( typeof inpSrcSelector === 'undefined' || typeof inpSrcTriggerSelector === 'undefined') {
throw new Error('wrong values in setImageSourceUrlInput');
}
inpSrc = document.querySelectorAll(inpSrcSelector)[0];
inpSrcTrigger = document.querySelectorAll(inpSrcTriggerSelector)[0];
inpSrcTriggerEvent = inpSrcTriggerEventVal || 'click';
inpSrcTrigger.addEventListener(inpSrcTriggerEvent, function() {
// imgSource.setAttribute('crossOrigin', 'Anonymous');
imgSource.src = inpSrc.value;
});
}
// set source from url string
function setUrlSource(url) {
var patt = /(https?:\/\/.*\.(?:png|jpg))/i;
// if (!patt.test(url)) {
// return;
// }
imgSource.src = url;
}
// set source from base64 string
function setBase64Source(string) {
imgSource.src = url;
}
// set crop trigger dom elemnt
function setCropTrigger(cropTriggerSelector, cropTriggerEventVal, callback) {
if ( typeof cropTriggerSelector === 'undefined') {
throw new Error('wrong values in setCropTrigger');
}
cropTrigger = document.querySelectorAll(cropTriggerSelector)[0];
cropTriggerEvent = cropTriggerEventVal || 'click';
// make a cropped image
// or send crop coordinates with image link
cropTrigger.addEventListener(cropTriggerEvent, function() {
// draw source image without a selection
drawSourceImage(imgSource, ctxLive, canvasLive);
try {
imgToCrop.src = canvasLive.toDataURL();
resizeCanvasToSelection(ctxCropped, canvasCropped);
} catch(e) {
// tainted = true;
var deScale = imgSource.width / source.w;
var temp = {
x: (sel.x - source.x) * deScale,
y: (sel.y - source.y) * deScale,
w: source.w * deScale,
h: source.h * deScale
};
// border cases recalculation
if (temp.x < 0 ) {
temp.w = temp.w + temp.x;
temp.x = 0;
}
if (temp.y < 0 ) {
temp.h = temp.h + temp.y;
temp.y = 0;
}
if ((temp.x + temp.w) > imgSource.width) {
temp.w = imgSource.width - temp.x;
}
if ((temp.y + temp.h) > imgSource.height) {
temp.h = imgSource.height - temp.y;
}
// resolve callback fn
callback({
url: imgSource.src,
x: temp.x,
y: temp.y,
w: temp.w,
h: temp.h,
});
}
// draw selection
drawSelection(ctxLive);
});
// draw image if loaded
imgToCrop.addEventListener('load', function() {
drawCropImage(imgToCrop, ctxCropped, canvasCropped);
// cache
var result = canvasCropped.toDataURL();
callback(result);
});
imgToCrop.addEventListener('error', function(e) {
log(e);
});
}
/******************************************************************
* API FUNCTIONS
******************************************************************/
//reset selection to default settings
function resetSelectionToDefault(canvas) {
var resetVals = {
x: source.x + source.w / 4,
y: source.y + source.h / 4,
w: source.w / 2,
h: source.h / 2
};
// log(resetVals);
for (prop in resetVals) {
sel[prop] = resetVals[prop];
}
}
function saveDragShiftValues(e, canvas) {
var x = e.clientX - canvas.getBoundingClientRect().left,
y = e.clientY - canvas.getBoundingClientRect().top;
// shift between click and left top corner of the selection area
sel.startDragShiftX = x - sel.x;
sel.startDragShiftY = y - sel.y;
// log(sel);
}
//
function saveMouseCoordinates(e, canvas) {
// click coords relative to the canvas
// @TODO shift to pageX, pageY
var x = e.clientX - canvas.getBoundingClientRect().left,
y = e.clientY - canvas.getBoundingClientRect().top,
// shift between click and left top corner of the sel
shiftX = x - sel.x,
shiftY = y - sel.y,
// central dividing reaction area coord lines
centerX = sel.x + sel.w / 2,
centerY = sel.y + sel.h / 2,
radius = (sel.w < sel.h) ? sel.w / 2 : sel.h / 2;
// radius-based calculation of dragging area
// if ( Math.abs(x - centerX) < radius && Math.abs(y - centerY) < radius) {
// log('drag');
// sel.x = x - sel.startDragShiftX;
// sel.y = y - sel.startDragShiftY;
// return;
// }
// square-based calculation of dragging area
if ((x > sel.x + sel.squareSize)
&& (x < (sel.x + sel.w - sel.squareSize))
&& (y > sel.y + sel.squareSize)
&& (y < (sel.y + sel.h - sel.squareSize))) {
// simple dragging
sel.x = x - sel.startDragShiftX;
sel.y = y - sel.startDragShiftY;
// cehcking borders
// if (sel.x > (source.x + sel.squareSize)
// && ((sel.x + sel.w) < (source.x + source.w - sel.squareSize))) {
// sel.x = x - sel.startDragShiftX;
// }
// if (sel.y > (source.y + sel.squareSize)
// && ((sel.y + sel.h) < (source.y + source.h - sel.squareSize))) {
// sel.y = y - sel.startDragShiftY;
// }
return;
}
// resizing
// top-left
if ( x < centerX && y < centerY) {
sel.x = x;
sel.y = y;
sel.w -= shiftX;
sel.h -= shiftY;
// top-right
} else if ( x > centerX && y < centerY) {
sel.y = y;
sel.w = x - sel.x;
sel.h -= shiftY;
// bottom-right
} else if ( x > centerX && y > centerY) {
sel.w = x - sel.x;
sel.h = y - sel.y;
// bottom-left
} else if ( x < centerX && y > centerY) {
sel.x = x;
sel.w -= shiftX;
sel.h = y - sel.y;
}
}
// resizes canvas to a parent element
function resizeCanvasToParentEl(ctx, canvas) {
var parentElRect = canvas.parentElement.getBoundingClientRect(),
parentElWidth = parentElRect.width,
parentElHeight = parentElRect.height;
// no need in these two
// canvas.width = parentElWidth;
// canvas.height = parentElHeight;
ctx.canvas.width = parentElWidth;
ctx.canvas.height = parentElHeight;
}
// resizes canvas to a particular image
function resizeCanvasToSelection(ctx, canvas) {
// canvas.width = sel.w;
// canvas.height = sel.h;
ctx.canvas.width = sel.w;
ctx.canvas.height = sel.h;
}
// redraw function aggregator
function drawCanvasLive() {
clearCanvas(ctxLive, canvasLive);
if (!source.x || !source.y || !source.w || !source.h) {
calculateSourceImagePos(imgSource, ctxLive, canvasLive);
}
drawSourceImage(imgSource, ctxLive, canvasLive);
drawSelection(ctxLive);
}
//
function calculateSourceImagePos(img, ctx, canvas) {
var x, y, w, h;
// @TODO: override to drag the whole selection
// scaling to live canvas
if (canvas.height > canvas.width) {
if (img.height > img.width) {
// log('vertical canvas - vertical image');
h = canvas.height;
w = img.width * h / img.height;
y = 0;
x = (canvas.width - w) / 2;
} else {
// log('vertical canvas - horizontal image');
w = canvas.width;
h = img.height * w / img.width;
x = 0;
y = (canvas.height - h) / 2;
}
} else {
if (img.height < img.width) {
// log('horizontal canvas - horizontal image');
h = canvas.height;
w = img.width * h / img.height;
y = 0;
x = (canvas.width - w) / 2;
} else {
// log('horizontal canvas - vertical image');
h = canvas.height;
w = img.width * h / img.height;
y = 0;
x = (canvas.width - w) / 2;
}
}
// preserve image absolute coords
source = {
x: x,
y: y,
w: w,
h: h
}
}
// draw loaded image to a canvas
function drawSourceImage(img, ctx, canvas) {
// drawing dark bg
ctx.beginPath();
ctx.drawImage(img, source.x, source.y, source.w, source.h);
ctx.fillStyle = 'rgba(0, 0, 0, .33)';
ctx.fillRect(source.x, source.y, source.w, source.h);
// drawing cropping area
ctx.save();
ctx.rect(sel.x, sel.y, sel.w, sel.h);
ctx.clip();
// drawing bright selection area
ctx.drawImage(img, source.x, source.y, source.w, source.h);
ctx.restore();
}
// draw loaded image to live canvas
function drawCropImage(img, ctx, canvas) {
ctx.drawImage(img, -sel.x, -sel.y);
}
// draw sel rectangle
// dotted = true - makes to draw dotted line without squares in the corners
// dotted = false - solid line with squares
function drawSelection(ctx, dotted) {
ctx.beginPath();
// draw squares in the corners
ctx.fillStyle = sel.lineColor;
// top-left
ctx.fillRect(sel.x - sel.squareSize / 2,
sel.y - sel.squareSize / 2,
sel.squareSize,
sel.squareSize);
// top-right
ctx.fillRect(sel.x + sel.w - sel.squareSize / 2,
sel.y - sel.squareSize / 2,
sel.squareSize,
sel.squareSize);
// bottom-right
ctx.fillRect(sel.x + sel.w - sel.squareSize / 2,
sel.y + sel.h - sel.squareSize / 2,
sel.squareSize,
sel.squareSize);
// bottom-left
ctx.fillRect(sel.x - sel.squareSize / 2,
sel.y + sel.h - sel.squareSize / 2,
sel.squareSize,
sel.squareSize);
// selection rectangle
ctx.rect(sel.x, sel.y, sel.w, sel.h);
ctx.lineWidth = sel.lineWidth;
ctx.strokeStyle = sel.lineColor;
ctx.stroke();
}
// clean canvas ctx
function clearCanvas(ctx, canvas) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
/******************************************************************
* FACADE
******************************************************************/
return {
setFileInput: setImageSourceFileInput,
setUrlInput: setImageSourceUrlInput,
setUrl: setUrlSource,
setBase64: setBase64Source,
setCropTrigger: setCropTrigger,
}
};