-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpa.js
More file actions
60 lines (49 loc) · 1.74 KB
/
pa.js
File metadata and controls
60 lines (49 loc) · 1.74 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
const canvas = document.getElementById('paintCanvas');
const ctx = canvas.getContext('2d');
let painting = false;
let color = document.getElementById('colorPicker').value;
let isEraser = false;
function startPosition(e) {
painting = true;
draw(e);
}
function endPosition() {
painting = false;
ctx.beginPath();
}
function draw(e) {
if (!painting) return;
ctx.lineWidth = 5;
ctx.lineCap = 'round';
ctx.strokeStyle = isEraser ? '#ffffff' : color;
ctx.lineTo(e.clientX - canvas.offsetLeft, e.clientY - canvas.offsetTop);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(e.clientX - canvas.offsetLeft, e.clientY - canvas.offsetTop);
}
function changeColor(e) {
if (!isEraser) {
color = e.target.value;
}
}
function clearCanvas() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
function toggleEraser() {
isEraser = true;
document.getElementById('selectPaintButton').classList.remove('active');
document.getElementById('eraserButton').classList.add('active');
}
function selectPaint() {
isEraser = false;
document.getElementById('eraserButton').classList.remove('active');
document.getElementById('selectPaintButton').classList.add('active');
}
canvas.addEventListener('mousedown', startPosition);
canvas.addEventListener('mouseup', endPosition);
canvas.addEventListener('mousemove', draw);
document.getElementById('colorPicker').addEventListener('input', changeColor);
document.getElementById('clearButton').addEventListener('click', clearCanvas);
document.getElementById('eraserButton').addEventListener('click', toggleEraser);
document.getElementById('selectPaintButton').addEventListener('click', selectPaint);
draw();