forked from codepo8/canvascropper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cropmenu.js
105 lines (99 loc) · 2.95 KB
/
cropmenu.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
var tothecroppa = function() {
var c = document.createElement( 'canvas' ),
cx = c.getContext( '2d' ),
img = null,
mousedown = false,
done = false,
detectevent = 'dblclick',
ic = {};
if ('contextMenu' in document.documentElement ) {
var menu = '<menu type="context" id="croppamenu">'+
'<menuitem label="crop" id="croppaitem" '+
' onclick="tothecroppa.initcrop()">'+
'</menuitem></menu>';
document.body.innerHTML += menu;
document.body.setAttribute( 'contextmenu', 'croppamenu' );
detectevent = 'contextmenu';
}
c.style.display = 'block';
c.style.position = 'absolute';
c.style.left = '-20000px';
c.style.top = 0;
document.body.appendChild( c );
document.body.addEventListener( detectevent, function( ev ) {
if ( ev.target.tagName === 'IMG' ) {
if ( detectevent === 'contextmenu' ) {
document.querySelector('#croppaitem').disabled = false;
}
img = ev.target;
ic = {
left: img.offsetLeft,
top: img.offsetTop,
width: img.offsetWidth,
height: img.offsetHeight
}
if ( detectevent === 'dblclick' ) {
initcrop();
}
} else {
if ( detectevent === 'contextmenu' ) {
document.querySelector('#croppaitem').disabled = true;
}
}
}, false);
c.addEventListener( 'mousemove', function( ev ) {
if ( mousedown && !done ) {
var mouse = [ ev.clientX - ic.left , ev.clientY - ic.top ];
cx.drawImage( img, 0, 0 );
cx.fillStyle = 'rgba( 0,0,0,0.8)';
rect = {
x: startx,
y: starty,
x1: mouse[0] - startx,
y1: mouse[1] - starty
};
cx.fillRect( 0, 0, rect.x, ic.height );
cx.fillRect( rect.x + rect.x1, 0, ic.width - rect.x1, ic.height );
cx.fillRect( rect.x, 0, rect.x1, rect.y );
cx.fillRect( rect.x, rect.y+rect.y1, rect.x1, ic.height - rect.y1 );
}
}, false );
c.addEventListener ( 'keydown', function( ev ) {
if ( ev.keyCode === 13 ) {
crop();
}
}, false );
c.addEventListener( 'mousedown', function( ev ) {
if ( !done ) {
mousedown = true;
startx = ( ev.clientX - ic.left );
starty = ( ev.clientY - ic.top );
}
},false);
c.addEventListener( 'dblclick', function( ev ) {
crop();
});
c.addEventListener( 'mouseup', function( ev ) {
mousedown = false;
}, false );
function crop() {
done = true;
c.width = rect.x1;
c.height = rect.y1;
cx.drawImage(
img, rect.x, rect.y, rect.x1, rect.y1, 0, 0, rect.x1, rect.y1
);
}
function initcrop(){
c.width = ic.width;
c.height = ic.height;
c.style.position = 'absolute';
c.style.top = ic.top + 'px';
c.style.left = ic.left + 'px';
img.style.visibility = 'hidden';
cx.drawImage( img, 0 ,0);
cx.fillStyle = 'rgba( 0,0,0,0.4)';
cx.fillRect( 0, 0, ic.width, ic.height );
};
return {initcrop:initcrop};
}();