-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathscript.js
More file actions
103 lines (83 loc) · 2.37 KB
/
script.js
File metadata and controls
103 lines (83 loc) · 2.37 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
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
100
101
102
103
const canvas = document.querySelector("canvas")
const ctx = canvas.getContext("2d")
const inputColor = document.querySelector(".input__color")
const tools = document.querySelectorAll(".button__tool")
const sizeButtons = document.querySelectorAll(".button__size")
const buttonClear = document.querySelector(".button__clear")
let brushSize = 20
let isPainting = false
let activeTool = "brush"
inputColor.addEventListener("change", ({ target }) => {
ctx.fillStyle = target.value
})
canvas.addEventListener("mousedown", ({ clientX, clientY }) => {
isPainting = true
if (activeTool == "brush") {
draw(clientX, clientY)
}
if (activeTool == "rubber") {
erase(clientX, clientY)
}
})
canvas.addEventListener("mousemove", ({ clientX, clientY }) => {
if (isPainting) {
if (activeTool == "brush") {
draw(clientX, clientY)
}
if (activeTool == "rubber") {
erase(clientX, clientY)
}
}
})
canvas.addEventListener("mouseup", ({ clientX, clientY }) => {
isPainting = false
})
const draw = (x, y) => {
ctx.globalCompositeOperation = "source-over"
ctx.beginPath()
ctx.arc(
x - canvas.offsetLeft,
y - canvas.offsetTop,
brushSize / 2,
0,
2 * Math.PI
)
ctx.fill()
}
const erase = (x, y) => {
ctx.globalCompositeOperation = "destination-out"
ctx.beginPath()
ctx.arc(
x - canvas.offsetLeft,
y - canvas.offsetTop,
brushSize / 2,
0,
2 * Math.PI
)
ctx.fill()
}
const selectTool = ({ target }) => {
const selectedTool = target.closest("button")
const action = selectedTool.getAttribute("data-action")
if (action) {
tools.forEach((tool) => tool.classList.remove("active"))
selectedTool.classList.add("active")
activeTool = action
}
}
const selectSize = ({ target }) => {
const selectedTool = target.closest("button")
const size = selectedTool.getAttribute("data-size")
sizeButtons.forEach((tool) => tool.classList.remove("active"))
selectedTool.classList.add("active")
brushSize = size
}
tools.forEach((tool) => {
tool.addEventListener("click", selectTool)
})
sizeButtons.forEach((button) => {
button.addEventListener("click", selectSize)
})
buttonClear.addEventListener("click", () => {
ctx.clearRect(0, 0, canvas.width, canvas.height)
})