-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcanvas.js
52 lines (48 loc) · 1.33 KB
/
canvas.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
window.addEventListener("load", (ev) => {
const canvas = document.querySelector("#canvas");
const ctx = canvas.getContext("2d");
canvas.height = window.innerHeight;
canvas.width = window.innerWidth;
let painting = false;
let points = [];
const startPainting = (ev) => {
console.log(ev);
painting = true;
points.push([]);
ctx.beginPath();
draw(ev);
};
const endPainting = () => {
painting = false;
};
const draw = (ev) => {
if (!painting) {
return;
}
points.slice(-1)[0].push(ev);
ctx.lineWidth = 10;
ctx.lineCap = "round";
ctx.lineTo(ev.clientX, ev.clientY);
ctx.stroke();
};
const undo = () => {
points.pop();
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (const lines of points) {
ctx.beginPath();
for (const ev of lines) {
ctx.lineTo(ev.clientX, ev.clientY);
ctx.stroke();
}
}
}
canvas.addEventListener("mousedown", (ev) => {
if (ev.button === 0) {
startPainting(ev);
} else if (ev.button === 2) {
undo();
}
});
canvas.addEventListener("mouseup", endPainting);
canvas.addEventListener("mousemove", draw);
});