-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
74 lines (63 loc) · 1.96 KB
/
app.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
// ----------VARIABLE------------
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
const brushWidth = document.querySelector('#brush-width');
const brushColor = document.querySelector('#color-picker');
const brush = document.querySelector('.brush');
const eraser = document.querySelector('.eraser');
const clearBtn = document.querySelector('.clear');
const saveBtn = document.querySelector('.save');
let isDrawing = false;
let currentWidth = 5;
let currentColor = '';
// -----------FUNCTIONS------------
function startDraw() {
isDrawing = true;
ctx.beginPath();
ctx.lineWidth = currentWidth;
}
function endDraw() {
isDrawing = false;
}
function drawing(e) {
if (!isDrawing) return
ctx.lineTo(e.offsetX, e.offsetY);
ctx.strokeStyle = `${currentColor}`;
ctx.stroke();
}
// ----------EVENTS----------
window.addEventListener('load', () => {
canvas.width = canvas.offsetWidth;
canvas.height = canvas.offsetHeight;
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, canvas.width, canvas.height);
})
canvas.addEventListener('mousedown', startDraw);
canvas.addEventListener('mousemove', drawing);
canvas.addEventListener('mouseup', endDraw);
brushWidth.addEventListener('change', () => {
currentWidth = brushWidth.value;
})
brushColor.addEventListener('change', () => {
currentColor = brushColor.value;
})
brush.addEventListener('click', () => {
brush.classList.add('active');
eraser.classList.remove('active');
currentColor = brushColor.value;
})
eraser.addEventListener('click', () => {
eraser.classList.add('active');
brush.classList.remove('active');
currentColor = 'white';
})
clearBtn.addEventListener('click', () => {
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, canvas.width, canvas.height);
})
saveBtn.addEventListener('click', () => {
let link = document.createElement('a');
link.download = `${Date.now()}.jpg`;
link.href = canvas.toDataURL();
link.click();
})