-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
126 lines (102 loc) · 2.73 KB
/
index.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
var h = require('hyperscript')
module.exports = function (img, selection_canvas, onCrop) {
if('function' === typeof selection_canvas)
onCrop = selection_canvas, selection_canvas = null
onCrop = onCrop || function () {}
selection_canvas = selection_canvas || h('canvas.hypercrop__selection', {width: 512, height: 512})
var width = img.width
var height = img.height
var canvas = h('canvas.hypercrop__canvas', {
width: width, height: height
})
canvas.selection = selection_canvas
var ctx = canvas.getContext('2d')
ctx.save()
var selection_ctx = selection_canvas.getContext('2d')
var down = false
function coords(ev) {
var rect = canvas.getBoundingClientRect()
return {
x: ((ev.clientX-rect.left)/rect.width)*width,
y: ((ev.clientY-rect.top)/rect.height)*height
}
}
var start, end
function square (start, end) {
var side = Math.max(
Math.abs(start.x - end.x),
Math.abs(start.y - end.y)
)
var topleft = {
x: (start.x < end.x) ? start.x : start.x - side,
y: (start.y < end.y) ? start.y : start.y - side
}
// reset the canvas
ctx.clearRect(
0, 0,
width, height
)
// fill the canvas with a translucent mask
ctx.fillStyle = 'rgba(0, 0, 0, 0.6)'
ctx.fillRect(
0, 0,
width, height
)
// cut a whole the the mask
ctx.clearRect(
topleft.x, topleft.y,
side, side
)
// apply the image over the mask with a compositor
ctx.globalCompositeOperation = 'source-out'
ctx.drawImage(img, 0, 0)
return {
topleft: topleft,
side: {
x: side,
y: side
}
}
}
function updateSelection () {
var bound = square(start, end)
selection_ctx.drawImage(img,
bound.topleft.x, bound.topleft.y,
bound.side.x, bound.side.y,
0, 0, selection_canvas.width, selection_canvas.height
)
}
canvas.onmousemove = function (e) {
if(!down) return
end = coords(e)
ctx.drawImage(img, 0, 0)
updateSelection()
}
canvas.onmousedown = function (ev) {
down = true
start = coords(ev)
end = null
}
canvas.onmouseup = function (ev) {
down = false
end = coords(ev)
onCrop(selection_canvas.toDataURL())
}
//default to select center square in image.
//with a small border to show the crop effect
var longest = Math.max(canvas.width, canvas.height)
var shortest = Math.min(canvas.width, canvas.height)
var edge = (longest - shortest)/2
var pad = 20
if(canvas.width > canvas.height)
start = {x: edge + pad, y: pad}
else
start = {x: pad, y: edge + pad}
end = {
x: start.x + shortest - 2*pad,
y: start.y + shortest - 2*pad
}
//default selection
updateSelection()
return canvas
}