-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
84 lines (64 loc) · 2.17 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
const gridTotalSize = 960;
let penMode = true;
let drawEnable = false;
updateGridSize();
document.body.addEventListener('keydown', (event) => {
if (event.key === 'd') drawEnable = true;
});
document.body.addEventListener('keyup', (event) => {
if (event.key === 'd') drawEnable = false;
});
const gridSizeInput = document.querySelector('#gridSizeInput');
gridSizeInput.addEventListener('change', updateGridSize);
const resetBtn = document.querySelector('#resetBtn');
resetBtn.addEventListener('click', updateGridSize);
const brushMode = document.querySelectorAll('input[name="brushMode"');
brushMode.forEach((brush) => brush.addEventListener('change', changePenMode));
function updateGridSize() {
const gridSizeInput = document.querySelector('#gridSizeInput');
const gridSizeLabel = gridSizeInput.previousElementSibling;
const drawingGrid = document.querySelector('.drawing-grid');
gridSizeLabel.textContent = `${gridSizeInput.value}×${gridSizeInput.value}`;
removeAllChildElements(drawingGrid);
generateDivGrid(drawingGrid, gridSizeInput.value);
}
function generateDivGrid(parentElement, sideLength) {
for (let i = 0; i < sideLength; i++) {
const pixelRow = document.createElement('div');
pixelRow.classList.add('pixel-row');
for (let i = 0; i < sideLength; i++) {
const pixel = document.createElement('div');
pixel.classList.add('pixel');
pixel.style.width = (gridTotalSize / sideLength) + 'px';
pixel.style.height = pixel.style.width;
pixel.addEventListener('mouseover', paintDiv);
pixelRow.appendChild(pixel);
}
parentElement.appendChild(pixelRow);
}
}
function removeAllChildElements(parentElement) {
while (parentElement.lastElementChild) {
parentElement.removeChild(parentElement.lastElementChild);
}
}
function paintDiv(event) {
const divElement = event.target;
if (drawEnable) {
if (penMode) {
divElement.classList.add('painted');
} else {
divElement.classList.remove('painted');
}
}
}
function changePenMode(event) {
let radioBtn = event.target;
if (radioBtn.checked) {
if (radioBtn.id === 'penMode') {
penMode = true;
} else {
penMode = false;
}
}
}