-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
71 lines (56 loc) · 1.58 KB
/
script.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
const canvas = document.querySelector('canvas');
const bar = document.querySelector('#bar');
const ctx = canvas.getContext('2d');
const download = document.querySelector("#download");
const canvasX = canvas.offsetLeft;
const canvasY = canvas.offsetTop;
canvas.width = window.innerWidth - canvasX;
canvas.height = window.innerHeight - canvasY;
ctx.fillStyle = "white";
ctx.fillRect(0, 0, canvas.width, canvas.height);
let isDrawing = false;
let lineWidth = 5;
let startX;
let startY;
bar.addEventListener('change', e => {
if(e.target.id === 'color') {
ctx.strokeStyle = e.target.value;
}
if(e.target.id === 'lineWidth') {
lineWidth = e.target.value;
}
});
bar.addEventListener('click', e => {
if (e.target.id === 'clear') {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "white";
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
});
const draw = (e) => {
if(!isDrawing) {
return;
}
ctx.lineWidth = lineWidth;
ctx.lineCap = 'round';
ctx.lineTo(e.clientX - canvasX, e.clientY);
ctx.stroke();
}
canvas.addEventListener('mousedown', (e) => {
isDrawing = true;
startX = e.clientX;
startY = e.clientY;
});
canvas.addEventListener('mouseup', e => {
isDrawing = false;
ctx.stroke();
ctx.beginPath();
});
canvas.addEventListener('mousemove', draw);
download.addEventListener('click', function (e) {
const link = document.createElement('a');
link.download = 'download.png';
link.href = canvas.toDataURL("image/png");
link.click();
link.delete;
});