-
Notifications
You must be signed in to change notification settings - Fork 900
/
Copy pathscript.js
99 lines (82 loc) · 2.5 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
// eraserSize.addEventListener("")
const canvas = document.querySelector("#draw");
const ctx = canvas.getContext("2d");
console.log(ctx);
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
ctx.strokeStyle = "#4400ff";
ctx.lineCap = "round";
ctx.lineJoin = "round";
let isDrawing = false;
let lastX = 0;
let lastY = 0;
let mode = "pen";
let lastColor = ctx.strokeStyle;
let lastWidth = 1;
let eraseWidth = 1;
const color = document.querySelector("input[type='color']");
const lineWidth = document.querySelector("input[type='number']");
const eraserSize = document.querySelector("input[type='range']");
const modePen = document.querySelector("#pen");
const modeErase = document.querySelector("#erase");
console.log(modePen);
console.log(modeErase);
function setColor() {
mode = "pen";
lastColor = this.value;
document.documentElement.style.setProperty(`--${this.type}`, `${this.value}`);
}
color.addEventListener("mousemove", setColor);
color.addEventListener("mouseover", setColor);
color.addEventListener("change", setColor);
function setLineWidth() {
mode = "pen";
lastWidth = this.value;
}
lineWidth.addEventListener("mousemove", setLineWidth);
lineWidth.addEventListener("mouseover", setLineWidth);
lineWidth.addEventListener("change", setLineWidth);
function setEraseSize() {
mode = "eraser";
eraseWidth = this.value;
document.documentElement.style.setProperty(
`--${mode}`,
`${this.value * 0.7}px`
);
}
eraserSize.addEventListener("mousemove", setEraseSize);
eraserSize.addEventListener("mouseover", setEraseSize);
eraserSize.addEventListener("change", setEraseSize);
function changeMode(newMode) {
mode = newMode;
}
modePen.addEventListener("click", () => changeMode("pen"));
modeErase.addEventListener("click", () => changeMode("eraser"));
function draw(e) {
if (!isDrawing) return;
ctx.beginPath();
ctx.moveTo(lastX, lastY);
ctx.lineTo(e.offsetX, e.offsetY);
if (mode === "pen") {
ctx.lineWidth = lastWidth;
ctx.strokeStyle = lastColor;
ctx.stroke();
} else {
ctx.strokeStyle = "#fff";
ctx.lineWidth = eraseWidth;
ctx.stroke();
}
[lastX, lastY] = [e.offsetX, e.offsetY];
console.log(ctx);
console.log(canvas);
}
canvas.addEventListener("mousemove", draw);
canvas.addEventListener("mousedown", e => {
isDrawing = true;
[lastX, lastY] = [e.offsetX, e.offsetY];
});
canvas.addEventListener("mouseup", e => {
isDrawing = false;
[lastX, lastY] = [e.offsetX, e.offsetY];
});
canvas.addEventListener("mouseout", () => (isDrawing = false));