-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
72 lines (56 loc) · 1.95 KB
/
script.js
File metadata and controls
72 lines (56 loc) · 1.95 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
const canvas = document.querySelector('canvas');
const context = canvas.getContext('2d');
const palette = document.getElementById('lineColor');
const brush = document.getElementById('lineWidth');
const clearButton = document.getElementById('clearBtn');
let brushColor = 'blue';
let brushWidth = '5';
let isDrawing = false;
const changeColor = function() {
brushColor = this.value;
};
const clearCanvas = function() {
context.clearRect(0, 0, canvas.width, canvas.height);
};
const changeWidth = function() {
brushWidth = this.value;
};
const start = function(event) {
isDrawing = true;
context.beginPath();
context.moveTo(event.clientX - canvas.offsetLeft, event.clientY - canvas.offsetTop);
};
const draw = function(event) {
if (isDrawing) {
if (event.which == 1) {
context.lineTo(event.clientX - canvas.offsetLeft, event.clientY - canvas.offsetTop);
context.strokeStyle = brushColor;
context.lineWidth = brushWidth;
context.lineCap = 'round';
context.lineJoin = 'round';
context.stroke();
} else if (event.which == 3) {
context.lineTo(event.clientX - canvas.offsetLeft, event.clientY - canvas.offsetTop);
context.strokeStyle = 'white';
context.lineWidth = brushWidth;
context.lineCap = 'round';
context.lineJoin = 'round';
context.stroke();
}
}
};
const stopDraw = function() {
if (isDrawing) {
context.closePath();
isDrawing = false;
}
};
canvas.addEventListener('mousedown', start);
canvas.addEventListener('mousemove', draw);
canvas.addEventListener('mouseup', stopDraw);
canvas.addEventListener('contextmenu', (event) => {
event.preventDefault();
})
palette.addEventListener('input', changeColor);
brush.addEventListener('input', changeWidth);
clearButton.addEventListener('click', clearCanvas);