-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
629 lines (558 loc) · 20 KB
/
index.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
let gridSize = 24;
const container = document.querySelector('.grid-container');
let bgColor = '#ffffff';
container.style.backgroundColor = bgColor;
//create new grid
function createGrid() {
let gridWidth = container.offsetWidth / gridSize;
container.style.gridTemplateColumns = `repeat(${gridSize - 3}, ${gridWidth}px) 1fr 1fr 1fr`;
container.style.gridTemplateRows = `repeat(${gridSize - 3}, ${gridWidth}px) 1fr 1fr 1fr`;
if (gridSize < 4) {
container.style.gridTemplateColumns = `repeat(${gridSize},1fr`;
container.style.gridTemplateRows = `repeat(${gridSize}, 1fr`;
}
for (let i = 0; i < gridSize ** 2; i++) {
const square = document.createElement('div');
square.classList.add('grid-item');
square.setAttribute('draggable', 'false');
square.style.backgroundColor = bgColor;
container.appendChild(square);
square.classList.add('border-top-left');
}
//add a right border
const rightItems = document.querySelectorAll(`.grid-item:nth-child(${gridSize}n)`);
for (let i = 0; i < rightItems.length; i++) {
rightItems[i].setAttribute('data-right', 'true');
rightItems[i].classList.toggle('border-right');
}
// add a bottom border
let gridItems = document.querySelectorAll('.grid-item');
const lastItems = Array.from(gridItems).slice(-`${gridSize}`);
for (let i = 0; i < lastItems.length; i++) {
lastItems[i].setAttribute('data-bottom', 'true');
lastItems[i].classList.toggle('border-bottom');
}
}
createGrid();
gridItems = document.querySelectorAll('.grid-item');
// set default colour to black
let ink = '#000000';
//pen color picker
const colorPicker = document.querySelector('#color-select');
colorPicker.addEventListener('input', (e) => {
ink = e.target.value;
if (grab) {
grab = false;
dropper.classList.remove('btn-on');
}
});
// backgraund color
const bgColorPicker = document.querySelector('#bg-color-select');
// toggle button colour when clicked
const buttons = document.getElementsByTagName('button');
for (let i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('click', () => {
buttons[i].classList.toggle('btn-on');
});
}
// gradually darken color
let shading = false;
const shaderButton = document.querySelector('#shader-btn');
shaderButton.addEventListener('click', () => {
if (shading) {
shading = false;
} else {
shading = true;
rainbow = false;
rainbowButton.classList.remove('btn-on');
lighten = false;
lightenButton.classList.remove('btn-on');
eraser = false;
eraserButton.classList.remove('btn-on');
}
if (grab) {
grab = false;
dropper.classList.remove('btn-on');
}
});
// gradually lighten the color
let lighten = false;
const lightenButton = document.querySelector('#lighten-btn');
lightenButton.addEventListener('click', () => {
if (lighten) {
lighten = false;
} else {
lighten = true;
shading = false;
shaderButton.classList.remove('btn-on');
rainbow = false;
rainbowButton.classList.remove('btn-on');
eraser = false;
eraserButton.classList.remove('btn-on');
}
if (grab) {
grab = false;
dropper.classList.remove('btn-on');
}
});
// shading function
function RGBToHex(rgb) {
// Choose correct separator
let sep = rgb.indexOf(',') > -1 ? ',' : ' ';
// Turn "rgb(r,g,b)" into [r,g,b]
rgb = rgb.substr(4).split(')')[0].split(sep);
let
r = (+rgb[0]).toString(16),
g = (+rgb[1]).toString(16),
b = (+rgb[2]).toString(16);
if (r.length == 1) r = '0' + r;
if (g.length == 1) g = '0' + g;
if (b.length == 1) b = '0' + b;
b = (+rgb[2]).toString(16);
if (r.length == 1) r = '0' + r;
if (g.length == 1) g = '0' + g;
if (b.length == 1) b = '0' + b;
return '#' + r + g + b;
}
function adjust(RGBToHex, rgb, amount) {
let color = RGBToHex(rgb);
return (
'#' +
color
.replace(/^#/, '')
.replace(/../g, (color) =>
('0' + Math.min(255, Math.max(0, parseInt(color, 16) + amount)).toString(16)).substr(-2)
)
);
}
// color capture tool
const dropper = document.querySelector('#color-grabber');
let grab = false;
dropper.addEventListener('click', () => {
// when grab is true, all drawing is frozen until a color is selected
if (grab) {
grab = false;
dropper.classList.remove('btn-on');
} else {
grab = true;
} if (fill) {
fill = false;
colorFillButton.classList.remove('btn-on');
}
});
// default eraser to false and listen for toggle
let eraser = false;
const eraserButton = document.querySelector('#eraser-btn');
eraserButton.addEventListener('click', () => {
if (eraser) {
eraser = false;
} else {
eraser = true;
shading = false;
shaderButton.classList.remove('btn-on');
rainbow = false;
rainbowButton.classList.remove('btn-on');
lighten = false;
lightenButton.classList.remove('btn-on');
}
if (grab) {
grab = false;
dropper.classList.remove('btn-on');
}
});
// default rainbow ink to false and listen for toggle
let rainbow = false;
const rainbowButton = document.querySelector('#rainbow-btn');
rainbowButton.addEventListener('click', () => {
if (rainbow) {
rainbow = false;
} else {
rainbow = true;
shading = false;
shaderButton.classList.remove('btn-on');
lighten = false;
lightenButton.classList.remove('btn-on');
eraser = false;
eraserButton.classList.remove('btn-on');
}
if (grab) {
grab = false;
dropper.classList.remove('btn-on');
}
});
//function to generate the rainbow
function randomColor() {
return `hsl(${Math.random() * 360}, 100%, 50%)`;
}
// slider to change the grid size
let progressBar = document.getElementById('progress-bar');
function rangeSlider(value) {
let gridLabels = document.querySelectorAll('#range-value');
progressBar.style.width = (value / 60) * 100 + '%';
for (let i = 0; i < gridLabels.length; i++) {
gridLabels[i].textContent = value;
}
gridSize = parseInt(value);
deleteGrid();
createGrid();
listen();
reInit();
// turn the grid button back on if it is off.
const gridButton = document.querySelector('#grid-btn');
if (gridButton.classList.contains('btn-on')) {
} else {
gridButton.classList.toggle('btn-on');
}
}
function reInit() {
deleteGrid();
createGrid();
listen();
}
function rangeSliderValue(value) {
let gridLabels = document.querySelectorAll('#range-value');
for (let i = 0; i < gridLabels.length; i++) {
gridLabels[i].textContent = value;
}
progressBar.style.width = (value / 60) * 100 + '%';
}
function deleteGrid() {
while (container.firstChild) {
container.removeEventListener('mousedown', drawClick);
container.removeEventListener('mouseenter', drawClickHover);
container.lastChild = null;
container.removeChild(container.lastChild);
}
}
//fade grid
function fadeGrid(item) {
// if the cell hasnt been coloured, set it to the background color (un marked cells are transperent)
if (item.style.backgroundColor == '' || item.style.backgroundColor == 'transperent') {
item.style.backgroundColor == bgColor;
}
// attatch class to each item. this fades the color to the background color over 1.5 seconds
// apply a random fadeout time to each item
let fadeSpeed = Math.random() * 10;
if (fadeSpeed > 8) {
item.classList.add('clear-fade');
} else if (fadeSpeed > 6) {
item.classList.add('clear-fade-2');
} else if (fadeSpeed > 4) {
item.classList.add('clear-fade-3');
} else if (fadeSpeed > 2) {
item.classList.add('clear-fade-4');
} else {
item.classList.add('clear-fade-5');
}
}
// clear grid with a fade out
let root = document.documentElement;
const clearButton = document.querySelector('#clear-grid');
function clearGrid() {
// sets the css background color to the js variable bgColor. this is so the fadeout class can be applied, and use its background color
root.style.setProperty('--bg-color', bgColor);
gridItems = document.querySelectorAll('.grid-item');
for (let i = 0; i < gridItems.length; i++) {
fadeGrid(gridItems[i]);
}
// set a timer so the fade has time to execute, then reset all the grid cells.
setTimeout(function () {
for (let i = 0; i < gridItems.length; i++) {
gridItems[i].style.backgroundColor = '';
gridItems[i].removeAttribute('data-inked');
gridItems[i].removeAttribute('data-shade');
gridItems[i].classList.remove('clear-fade');
gridItems[i].classList.remove('clear-fade-2');
gridItems[i].classList.remove('clear-fade-3');
gridItems[i].classList.remove('clear-fade-4');
gridItems[i].classList.remove('clear-fade-5');
}
}, 1500);
container.style.backgroundColor = bgColor;
// turn off the button after a very short delay
setTimeout(function () {
clearButton.classList.remove('btn-on');
}, 1400);
}
clearButton.addEventListener('click', clearGrid);
// set fill to true when the color fill button is pressed
// if fill is true set it to false (clicking the button without filling)
// when fill is true all other events on the grid will stop and listen for a grid area to fill
const colorFillButton = document.querySelector('#color-fill');
let fill = false;
colorFillButton.addEventListener('click', () => {
if (grab) {
grab = false;
dropper.classList.remove('btn-on');
}
if (fill) {
fill = false;
} else {
fill = true;
}
});
// convert array into matrix representing the grid
function toMatrix(arr, width) {
return arr.reduce(function (rows, key, index) {
return (index % width == 0 ? rows.push([key]) : rows[rows.length - 1].push(key)) && rows;
}, []);
}
function hexToRGB(hex) {
let r = parseInt(hex[1] + hex[2], 16);
let g = parseInt(hex[3] + hex[4], 16);
let b = parseInt(hex[5] + hex[6], 16);
return `rgb(${r}, ${g}, ${b})`;
}
function findNeighbors(matrix, x, y, oldColor, newColor) {
const possibleNeighbors = [
{ cell: matrix?.[x]?.[y - 1], x: x, y: y - 1 }, // west
{ cell: matrix?.[x]?.[y + 1], x: x, y: y + 1 }, // east
{ cell: matrix?.[x - 1]?.[y], x: x - 1, y: y }, // north
{ cell: matrix?.[x + 1]?.[y], x: x + 1, y: y }, // south
];
const neighbors = [];
for (const neighbor of possibleNeighbors) {
if (
neighbor.cell !== undefined &&
neighbor.cell.style.backgroundColor === oldColor &&
neighbor.cell.style.backgroundColor !== newColor
) {
neighbors.push(neighbor);
}
}
return neighbors;
}
function floodFill(image, x, y, oldColor, newColor) {
if (oldColor === newColor) return;
oldColor = hexToRGB(oldColor);
newColor = hexToRGB(newColor);
const toPaint = [{ x: x, y: y }]; // queue
while (toPaint.length > 0) {
const { x, y } = toPaint.shift();
const neighbors = findNeighbors(image, x, y, oldColor, newColor);
for (const { cell, x, y } of neighbors) {
toPaint.push({ x, y });
cell.style.backgroundColor = rainbow ? randomColor() : newColor;
cell.setAttribute('data-inked', 'true');
}
}
}
//colorfill
function colorFill(e) {
if (fill) {
//get index of the clicked grid cell
const ogIndex = Array.from(e.target.parentElement.children).indexOf(
e.target
);
// console.log(ogIndex);
gridItems = document.querySelectorAll('.grid-item');
const gridItemsArray = Array.from(gridItems);
// console.log(gridItemsArray.length);
// create grid-like representation of grid items
const gridItemsArray2D = toMatrix(gridItemsArray, gridSize);
// get index of clicked item in 2d array
const gridX = Math.floor(ogIndex / gridSize);
const gridY = ogIndex % gridSize;
const seed = gridItemsArray2D[gridX][gridY];
const oldInk = seed.style.backgroundColor
? RGBToHex(seed.style.backgroundColor)
: bgColor;
floodFill(gridItemsArray2D, gridX, gridY, oldInk, ink);
colorFillButton.classList.remove('btn-on');
fill = false;
}
}
// draw on the grid when clicked
function drawClick(e) {
// when fill or grab is true do not do anything (a seperate listener is waiting for fill / grab input)
if (!grab && !fill) {
if (eraser) {
e.target.style.backgroundColor = '';
//data-inked = true means the background color change wont affect these elements
e.target.removeAttribute('data-inked');
e.target.removeAttribute('data-shade');
} else if (rainbow) {
e.target.style.backgroundColor = randomColor();
e.target.setAttribute('data-inked', 'true');
e.target.removeAttribute('data-shade');
} else if (shading) {
// first check to see if this grid item has been shadded. if it hasnt, set data-shade to 1
// this is nessesarry to transfer shading between bg color changes
if (!e.target.dataset.shade) {
e.target.setAttribute('data-shade', '1');
} else {
// if the grid item has been shadded, increment the data-shade value
// this keeps track of how many times the grid item has been shaded
let shadeAmount = parseInt(e.target.getAttribute('data-shade'));
shadeAmount++;
e.target.setAttribute('data-shade', `${shadeAmount}`);
} // a transperent item cant be shadded. if item is transperent first set the cell color to bg color
if (e.target.style.backgroundColor == '' || e.target.style.backgroundColor == 'transperent') {
e.target.style.backgroundColor = bgColor;
}
e.target.style.backgroundColor = adjust(RGBToHex, e.target.style.backgroundColor, -15);
// e.target.setAttribute('data-inked', 'true');
} else if (lighten) {
if (!e.target.dataset.shade) {
e.target.setAttribute('data-shade', '-1');
} else {
// if the grid item has been lightened, decrement the data-shade value
// this keeps track of how many times the grid item has been shaded
let shadeAmount = parseInt(e.target.getAttribute('data-shade'));
shadeAmount--;
e.target.setAttribute('data-shade', `${shadeAmount}`);
}
if (e.target.style.backgroundColor == '' || e.target.style.backgroundColor == 'transperent') {
e.target.style.backgroundColor = bgColor;
}
e.target.style.backgroundColor = adjust(RGBToHex, e.target.style.backgroundColor, +15);
// e.target.setAttribute('data-inked', 'true');
} else {
e.target.style.backgroundColor = ink;
e.target.setAttribute('data-inked', 'true');
e.target.removeAttribute('data-shade');
}
}
}
// draw when hovering into a grid with the mouse held down
function drawClickHover(e) {
if (e.buttons > 0) {
if (!grab && !fill) {
if (eraser) {
e.target.style.backgroundColor = '';
//data-inked = true means the background color change wont affect these elements
e.target.removeAttribute('data-inked');
e.target.removeAttribute('data-shade');
} else if (rainbow) {
e.target.style.backgroundColor = randomColor();
e.target.setAttribute('data-inked', 'true');
e.target.removeAttribute('data-shade');
} else if (shading) {
// first check to see if this grid item has been shadded. if it hasnt, set data-shade to 1
// this is nessesarry to transfer shading between bg color changes
if (!e.target.dataset.shade) {
e.target.setAttribute('data-shade', '1');
} else {
// if the grid item has been shadded, increment the data-shade value
// this keeps track of how many times the grid item has been shaded
let shadeAmount = parseInt(e.target.getAttribute('data-shade'));
shadeAmount++;
e.target.setAttribute('data-shade', `${shadeAmount}`);
} // a transperent item cant be shadded. if item is transperent first set the cell color to bg color
if (
e.target.style.backgroundColor == '' ||
e.target.style.backgroundColor == 'transperent'
) {
e.target.style.backgroundColor = bgColor;
}
e.target.style.backgroundColor = adjust(RGBToHex, e.target.style.backgroundColor, -15);
// e.target.setAttribute('data-inked', 'true');
} else if (lighten) {
if (!e.target.dataset.shade) {
e.target.setAttribute('data-shade', '-1');
} else {
// if the grid item has been lightened, decrement the data-shade value
// this keeps track of how many times the grid item has been shaded
let shadeAmount = parseInt(e.target.getAttribute('data-shade'));
shadeAmount--;
e.target.setAttribute('data-shade', `${shadeAmount}`);
}
if (
e.target.style.backgroundColor == '' ||
e.target.style.backgroundColor == 'transperent'
) {
e.target.style.backgroundColor = bgColor;
}
e.target.style.backgroundColor = adjust(RGBToHex, e.target.style.backgroundColor, +15);
// e.target.setAttribute('data-inked', 'true');
} else {
e.target.style.backgroundColor = ink;
e.target.setAttribute('data-inked', 'true');
e.target.removeAttribute('data-shade');
}
}
}
}
// listen for events
function listen() {
gridItems = document.querySelectorAll('.grid-item');
for (let i = 0; i < gridItems.length; i++) {
gridItems[i].addEventListener('mousedown', drawClick);
// listen for a mouse over and change colour only if mouse button is pressed
gridItems[i].addEventListener('mouseenter', drawClickHover);
}
//listen for clicks on all grid items when grab is true (color picker)
for (let i = 0; i < gridItems.length; i++) {
gridItems[i].addEventListener('click', (e) => {
if (grab) {
ink = e.target.style.backgroundColor;
// if trying to grab the color of the background (transperent cell)
if (ink == '') {
colorPicker.value = bgColor;
} else {
colorPicker.value = RGBToHex(ink);
}
dropper.classList.remove('btn-on');
grab = false;
// once color has been grabbed, turn off other buttons so you can draw with the new color without
// having to toggle the other button manually
rainbow = false;
rainbowButton.classList.remove('btn-on');
shading = false;
shaderButton.classList.remove('btn-on');
lighten = false;
lightenButton.classList.remove('btn-on');
eraser = false;
eraserButton.classList.remove('btn-on');
}
});
}
// listen for clicks on all grid items when fill is true (colour fill)
for (let i = 0; i < gridItems.length; i++) {
gridItems[i].addEventListener('click', colorFill);
}
bgColorPicker.addEventListener('input', (e) => {
gridItems = document.querySelectorAll('.grid-item');
bgColor = e.target.value;
for (let i = 0; i < gridItems.length; i++) {
if (!gridItems[i].dataset.inked) {
container.style.backgroundColor = bgColor;
}
// carry over shading when the bg color changes
//set all shaded items to bg color, so that the shading ran be re-applyed to the new bg color
// dont change the color of shaded inked cells, only background cells that have been shaded
if (!gridItems[i].dataset.inked) {
if (gridItems[i].dataset.shade) {
gridItems[i].style.backgroundColor = bgColor;
// grab the value of data-shade (the amount of times the cell has been shaded)
let shadeAmount = parseInt(gridItems[i].getAttribute('data-shade'));
// multiply the default shading intensity by shadeAmount, then apply this ammount
//of shading to the cell
let reshadeValue = shadeAmount * -15;
gridItems[i].style.backgroundColor = adjust(
RGBToHex,
gridItems[i].style.backgroundColor,
reshadeValue
);
}
}
}
});
// toggle grid lines
const gridButton = document.querySelector('#grid-btn');
gridButton.addEventListener('click', () => {
for (i = 0; i < gridItems.length; i++) {
//toggle top and left cell borders
gridItems[i].classList.toggle('border-top-left');
//toggle the remaining right borders
if (gridItems[i].dataset.right) {
gridItems[i].classList.toggle('border-right');
}
// toggle the remaining bottom borders
if (gridItems[i].dataset.bottom) {
gridItems[i].classList.toggle('border-bottom');
}
}
});
}
listen();