-
Notifications
You must be signed in to change notification settings - Fork 0
/
pic_rotate.js
74 lines (65 loc) · 1.59 KB
/
pic_rotate.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
const ctx = canvas.getContext("2d");
let rotateDegree = 0;
let objUrl = null;
function addImage(src) {
const image = new Image();
image.onload = drawImageRotated;
image.src = src;
}
function drawImageRotated() {
if (rotateDegree % 180 == 0) {
canvas.width = this.naturalWidth;
canvas.height = this.naturalHeight;
} else {
canvas.width = this.naturalHeight;
canvas.height = this.naturalWidth;
}
ctx.save();
ctx.rotate(rotateDegree * Math.PI / 180);
switch (rotateDegree) {
case 0: ctx.drawImage(this, 0, 0); break;
case 90: ctx.drawImage(this, 0, -canvas.width); break;
case 180: ctx.drawImage(this, -canvas.width, -canvas.height); break;
case 270: ctx.drawImage(this, -canvas.height, 0); break;
}
ctx.restore();
}
inputImg.addEventListener('change', function(e) {
if (this.files.length == 0) {
reset();
return;
}
clearObjUrl();
objUrl = URL.createObjectURL(this.files[0]);
addImage(objUrl);
});
btnRotate.addEventListener('click', function(e) {
clearCanvas();
if (!objUrl) return;
rotateDegree += 90;
if (rotateDegree == 360) {
rotateDegree = 0;
}
addImage(objUrl);
});
btnDownload.addEventListener('click', function(e) {
const a = document.createElement('a');
a.href = canvas.toDataURL(`image/${paramMime.value}`, 1);
a.download = `rotated.${paramMime.value}`;
a.click();
a.remove();
});
function reset() {
clearObjUrl();
clearCanvas();
}
function clearObjUrl() {
if (objUrl) {
window.URL.revokeObjectURL(objUrl);
objUrl = null;
}
}
function clearCanvas() {
canvas.width = 0;
canvas.height = 0;
}