-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
98 lines (83 loc) · 2.62 KB
/
app.js
File metadata and controls
98 lines (83 loc) · 2.62 KB
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
$(document).ready(function () {
const $canvas = $("#signatureCanvas");
const canvas = $canvas[0];
const ctx = canvas.getContext("2d");
const $clearBtn = $("#clearBtn");
const $undoBtn = $("#undoBtn");
const $redoBtn = $("#redoBtn");
const $saveBtn = $("#saveBtn");
const $savedImage = $("#savedImage");
const $downloadLink = $("#downloadLink");
let isDrawing = false;
let drawHistory = [];
let historyIndex = -1;
canvas.width = $canvas.width();
canvas.height = $canvas.height();
$canvas.on("mousedown", function (e) {
isDrawing = true;
ctx.beginPath();
ctx.moveTo(e.offsetX, e.offsetY);
});
$canvas.on("mousemove", function (e) {
if (isDrawing) {
ctx.lineTo(e.offsetX, e.offsetY);
ctx.strokeStyle = "#000";
ctx.lineWidth = 2;
ctx.stroke();
}
});
$canvas.on("mouseup mouseleave", function () {
isDrawing = false;
saveState();
});
function saveState() {
if (historyIndex < drawHistory.length - 1) {
drawHistory = drawHistory.slice(0, historyIndex + 1);
}
drawHistory.push(canvas.toDataURL());
historyIndex++;
}
function undo() {
if (historyIndex > 0) {
historyIndex--;
const previousState = drawHistory[historyIndex];
const img = new Image();
img.src = previousState;
img.onload = function () {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0);
};
}
}
function redo() {
if (historyIndex < drawHistory.length - 1) {
historyIndex++;
const nextState = drawHistory[historyIndex];
const img = new Image();
img.src = nextState;
img.onload = function () {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0);
};
}
}
$clearBtn.on("click", function () {
ctx.clearRect(0, 0, canvas.width, canvas.height);
$savedImage.hide();
drawHistory = [];
historyIndex = -1;
});
$undoBtn.on("click", function () {
undo();
});
$redoBtn.on("click", function () {
redo();
});
$saveBtn.on("click", function () {
const dataURL = canvas.toDataURL("image/png");
$savedImage.attr("src", dataURL).show();
$downloadLink.attr("href", dataURL);
$downloadLink.attr("download", `signature_${Date.now()}.png`);
$downloadLink[0].click();
});
});