-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
235 lines (196 loc) · 6.59 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
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
const classNames = {
bodyDark: 'body_dark',
controlItem: 'color-item',
controlItemActive: 'control-item_active',
controlItemDark: 'color-item_dark',
}
const urls = {
random: 'https://picsum.photos/600/400',
}
const containers = {
content: document.getElementById('content'),
image: document.getElementById('image-container'),
colors: document.getElementById('colors-container'),
}
const controls = {
randomButton: document.getElementById('control-random'),
uploadButton: document.getElementById('control-upload'),
medianCutButton: document.getElementById('control-median-cut'),
kMeansButton: document.getElementById('control-k-means'),
histogramButton: document.getElementById('control-histogram'),
fileInput: document.getElementById('file-input'),
}
let currentClusteringMode;
const clusteringModes = {
medianCut: {
button: controls.medianCutButton,
action: applyMedianCut,
},
kMeans: {
button: controls.kMeansButton,
action: applyKMeans,
},
histogram: {
button: controls.histogramButton,
action: applyHistogram,
},
}
function copyToClipboard(text) {
const textarea = document.createElement('textarea');
textarea.value = text;
textarea.setAttribute('readonly', '');
textarea.style.position = 'absolute';
textarea.style.left = '-9999px';
textarea.style.opacity = 0;
document.body.appendChild(textarea);
textarea.select();
document.execCommand('copy');
document.body.removeChild(textarea);
}
function setClusteringMode(mode) {
currentClusteringMode = mode;
Object.values(clusteringModes).forEach(clusteringMode => {
clusteringMode.button.classList.remove(classNames.controlItemActive);
});
currentClusteringMode.button.classList.add(classNames.controlItemActive);
}
function loadImage(url, onSuccess) {
const imageElement = new Image();
imageElement.crossOrigin = '*';
imageElement.onload = function () {
onSuccess(this);
}
imageElement.src = url;
containers.image.innerHTML = '';
containers.image.appendChild(imageElement);
}
function getCurrentImage() {
return containers.image.getElementsByTagName('img')[0];
}
function getImagePixels(image) {
const width = image.naturalWidth;
const height = image.naturalHeight;
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d');
ctx.drawImage(image, 0, 0);
const imageData = ctx.getImageData(0, 0, width, height);
const pixels = [];
const countPixels = imageData.width * imageData.height;
const ratioCountPixels = 600 * 400;
const ratio = Math.min(Math.floor(countPixels / ratioCountPixels), 5);
const pixelStep = Math.pow(2, ratio);
for (let x = 0; x < countPixels; x += pixelStep) {
const index = x * 4;
pixels.push([
imageData.data[index],
imageData.data[index + 1],
imageData.data[index + 2],
]);
}
return pixels;
}
function getAverageClusterColor(cluster) {
return cluster
.reduce((sum, pixel) => {
return sum.map((value, index) => value + pixel[index]);
}, [0, 0, 0])
.map(value => Math.floor(value / cluster.length));
}
function getColorLightness([r, g, b]) {
const cr = r / 255;
const cg = g / 255;
const cb = b / 255;
const cmin = Math.min(cr, cg, cb);
const cmax = Math.max(cr, cg, cb);
return (cmax + cmin) / 2;
}
function getHexColor(pixel) {
const hexValue = pixel.map(value => value.toString(16).padStart(2, '0'))
.join('')
return `#${hexValue}`;
}
function getRGBColor([r, g, b]) {
return `rgb(${r}, ${g}, ${b})`;
}
function createColorElement(pixel) {
const hexString = getHexColor(pixel);
const rgbString = getRGBColor(pixel);
const colorLightness = getColorLightness(pixel);
const element = document.createElement('div');
element.addEventListener('click', () => copyToClipboard(hexString));
element.innerText = hexString;
element.style.background = rgbString;
element.classList.add(classNames.controlItem);
colorLightness > 0.5 && element.classList.add(classNames.controlItemDark);
return element;
}
function updateColors(clusters) {
const fragment = document.createDocumentFragment();
clusters.forEach((cluster, index) => {
const pixel = getAverageClusterColor(cluster);
const colorElement = createColorElement(pixel);
fragment.appendChild(colorElement);
if (index === 0) {
const mainColorHex = getHexColor(pixel);
const mainColorLightness = getColorLightness(pixel);
document.body.style.background = mainColorHex;
mainColorLightness > 0.5
? document.body.classList.add(classNames.bodyDark)
: document.body.classList.remove(classNames.bodyDark);
}
});
containers.colors.innerHTML = '';
containers.colors.appendChild(fragment);
}
function generateMedianCut(pixels) {
const clusters = MedianCutClusterizer.getClusters(pixels, 2);
updateColors(clusters);
}
function generateKMeansColors(pixels) {
const clusters = KMeansClusterizer.getClusters(pixels, 4, 1);
updateColors(clusters);
}
function generateHistogramColors(pixels) {
const clusters = Histogram.getClusters(pixels);
updateColors(clusters);
}
function applyMedianCut(image) {
const pixels = getImagePixels(image);
generateMedianCut(pixels);
}
function applyKMeans(image) {
const pixels = getImagePixels(image);
generateKMeansColors(pixels);
}
function applyHistogram(image) {
const pixels = getImagePixels(image);
generateHistogramColors(pixels);
}
function setImageLink(url) {
loadImage(url, image => {
currentClusteringMode.action(image);
});
}
function setRandomImage() {
const imageLink = `${urls.random}?id=${Math.random() * 999999}`;
setImageLink(imageLink);
}
controls.fileInput.addEventListener('change', function () {
if (this.files && this.files[0]) {
const url = URL.createObjectURL(this.files[0]);
setImageLink(url);
this.value = '';
}
});
controls.randomButton.addEventListener('click', () => setRandomImage());
controls.uploadButton.addEventListener('click', () => controls.fileInput.click());
Object.values(clusteringModes).forEach(clusteringMode => {
clusteringMode.button.addEventListener('click', () => {
setClusteringMode(clusteringMode);
clusteringMode.action(getCurrentImage());
});
});
setClusteringMode(clusteringModes.histogram);
setRandomImage();