-
Notifications
You must be signed in to change notification settings - Fork 2
/
colorcue.js
377 lines (353 loc) · 12.9 KB
/
colorcue.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
// ===== functions to apply daltonization to images and single colors
/*
Algorithm Source:
Color.Vision.Daltonize : v0.1
------------------------------
"Analysis of Color Blindness" by Onur Fidaner, Poliang Lin and Nevran Ozguven.
Note: the original link is broken, below is an archive of the paper
https://web.archive.org/web/20090731011248/http://scien.stanford.edu/class/psych221/projects/05/ofidaner/project_report.pdf
"Digital Video Colourmaps for Checking the Legibility of Displays by Dichromats" by Françoise Viénot, Hans Brettel and John D. Mollon
http://vision.psychol.cam.ac.uk/jdmollon/papers/colourmaps.pdf
*/
let daltonizeImage = function (image, options) {
var CVDMatrix = { // Color Vision Deficiency
"Protanopia": [ // reds are greatly reduced (1% men)
0.0, 2.02344, -2.52581,
0.0, 1.0, 0.0,
0.0, 0.0, 1.0
],
"Deuteranopia": [ // greens are greatly reduced (1% men)
1.0, 0.0, 0.0,
0.494207, 0.0, 1.24827,
0.0, 0.0, 1.0
],
"Tritanopia": [ // blues are greatly reduced (0.003% population)
1.0, 0.0, 0.0,
0.0, 1.0, 0.0,
-0.395913, 0.801109, 0.0
]
};
if (!options) options = {};
if (image.width === 0 || image.height === 0) return;
var type = typeof options.type == "string" ? options.type : "Normal";
// this line is useless
// amount = typeof options.amount == "number" ? options.amount : 1.0;
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = image.width;
canvas.height = image.height;
// arguments: (image, xoffset, yoffset, width, height)
// https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/drawImage
ctx.drawImage(image, 0, 0, image.width, image.height);
try {
var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
var data = imageData.data;
} catch (e) {
console.error(e);
}
// Apply Daltonization
var cvd = CVDMatrix[type],
cvd_a = cvd[0],
cvd_b = cvd[1],
cvd_c = cvd[2],
cvd_d = cvd[3],
cvd_e = cvd[4],
cvd_f = cvd[5],
cvd_g = cvd[6],
cvd_h = cvd[7],
cvd_i = cvd[8];
var L, M, S, l, m, s, R, G, B, RR, GG, BB;
for (var id = 0, length = data.length; id < length; id += 4) {
var r = data[id],
g = data[id + 1],
b = data[id + 2];
// RGB to LMS matrix conversion
L = (17.8824 * r) + (43.5161 * g) + (4.11935 * b);
M = (3.45565 * r) + (27.1554 * g) + (3.86714 * b);
S = (0.0299566 * r) + (0.184309 * g) + (1.46709 * b);
// Simulate color blindness
l = (cvd_a * L) + (cvd_b * M) + (cvd_c * S);
m = (cvd_d * L) + (cvd_e * M) + (cvd_f * S);
s = (cvd_g * L) + (cvd_h * M) + (cvd_i * S);
// LMS to RGB matrix conversion
R = (0.0809444479 * l) + (-0.130504409 * m) + (0.116721066 * s);
G = (-0.0102485335 * l) + (0.0540193266 * m) + (-0.113614708 * s);
B = (-0.000365296938 * l) + (-0.00412161469 * m) + (0.693511405 * s);
// Isolate invisible colors to color vision deficiency (calculate error matrix)
R = r - R;
G = g - G;
B = b - B;
// Shift colors towards visible spectrum (apply error modifications)
RR = (0.0 * R) + (0.0 * G) + (0.0 * B);
GG = (0.7 * R) + (1.0 * G) + (0.0 * B);
BB = (0.7 * R) + (0.0 * G) + (1.0 * B);
// Add compensation to original values
R = RR + r;
G = GG + g;
B = BB + b;
// Clamp values
if (R < 0) R = 0;
if (R > 255) R = 255;
if (G < 0) G = 0;
if (G > 255) G = 255;
if (B < 0) B = 0;
if (B > 255) B = 255;
// Record color
data[id] = R >> 0;
data[id + 1] = G >> 0;
data[id + 2] = B >> 0;
}
// Record data
ctx.putImageData(imageData, 0, 0);
if (typeof options.callback == "function") {
options.callback(canvas);
}
};
let daltonizeRGB = function ([red, green, blue], options) {
var CVDMatrix = { // Color Vision Deficiency
"Protanopia": [ // reds are greatly reduced (1% men)
0.0, 2.02344, -2.52581,
0.0, 1.0, 0.0,
0.0, 0.0, 1.0
],
"Deuteranopia": [ // greens are greatly reduced (1% men)
1.0, 0.0, 0.0,
0.494207, 0.0, 1.24827,
0.0, 0.0, 1.0
],
"Tritanopia": [ // blues are greatly reduced (0.003% population)
1.0, 0.0, 0.0,
0.0, 1.0, 0.0,
-0.395913, 0.801109, 0.0
]
};
if (!options) options = {};
var type = typeof options.type == "string" ? options.type : "Normal";
// this line is useless
// var amount = typeof options.amount == "number" ? options.amount : 1.0;
// Apply Daltonization
var cvd = CVDMatrix[type],
cvd_a = cvd[0],
cvd_b = cvd[1],
cvd_c = cvd[2],
cvd_d = cvd[3],
cvd_e = cvd[4],
cvd_f = cvd[5],
cvd_g = cvd[6],
cvd_h = cvd[7],
cvd_i = cvd[8];
var L, M, S, l, m, s, R, G, B, RR, GG, BB;
data = [red, green, blue];
var r = data[0],
g = data[1],
b = data[2];
// RGB to LMS matrix conversion
L = (17.8824 * r) + (43.5161 * g) + (4.11935 * b);
M = (3.45565 * r) + (27.1554 * g) + (3.86714 * b);
S = (0.0299566 * r) + (0.184309 * g) + (1.46709 * b);
// Simulate color blindness
l = (cvd_a * L) + (cvd_b * M) + (cvd_c * S);
m = (cvd_d * L) + (cvd_e * M) + (cvd_f * S);
s = (cvd_g * L) + (cvd_h * M) + (cvd_i * S);
// LMS to RGB matrix conversion
R = (0.0809444479 * l) + (-0.130504409 * m) + (0.116721066 * s);
G = (-0.0102485335 * l) + (0.0540193266 * m) + (-0.113614708 * s);
B = (-0.000365296938 * l) + (-0.00412161469 * m) + (0.693511405 * s);
// Isolate invisible colors to color vision deficiency (calculate error matrix)
R = r - R;
G = g - G;
B = b - B;
// Shift colors towards visible spectrum (apply error modifications)
RR = (0.0 * R) + (0.0 * G) + (0.0 * B);
GG = (0.7 * R) + (1.0 * G) + (0.0 * B);
BB = (0.7 * R) + (0.0 * G) + (1.0 * B);
// Add compensation to original values
R = RR + r;
G = GG + g;
B = BB + b;
// Clamp values
if (R < 0) R = 0;
if (R > 255) R = 255;
if (G < 0) G = 0;
if (G > 255) G = 255;
if (B < 0) B = 0;
if (B > 255) B = 255;
// Record color
data[0] = R >> 0;
data[1] = G >> 0;
data[2] = B >> 0;
return data
};
// https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_colors/Applying_color
const colorOptions = [
'color',
'background-color',
'text-shadow',
'text-decoration-color',
'text-emphasis-color',
'caret-color',
'column-rule-color',
'outline-color',
'border-color',
'border-left-color',
'border-right-color',
'border-top-color',
'border-bottom-color',
'border-block-start-color',
'border-block-end-color',
'border-inline-start-color',
'border-inline-end-color',
'fill',
'stroke'
]
function adjustColors(element, options) {
// Recursively adjust colors on all child nodes of the given element.
if (element.childNodes.length) {
element.childNodes.forEach(function (child) {
adjustColors(child, options);
});
}
if (element.nodeType === Node.ELEMENT_NODE) {
colorOptions.forEach((property) => {
const color = window.getComputedStyle(element)[property]
if (color == 'none') {
return
}
element.style[property] = adjustSingleColor(color, options)
})
}
}
function adjustSingleColor(input, options) {
const rgbRegex = /rgb\((\s*\d+\s*,\s*\d+\s*,\s*\d+\s*)\)/g;
const rgbaRegex = /rgba\((\s*\d+\s*,\s*\d+\s*,\s*\d+\s*,\s*\d+(\.\d+)?\s*)\)/g;
let resultString
if (rgbRegex.test(input)) {
resultString = input.replace(rgbRegex, (match) => {
// split rgb() string into r, g, b integers
const valuesArray = match.split(',').map((value, i) => {
if (i == 0) {
value = value.substr(4)
}
return parseInt(value.trim(), 10)
}
);
// daltonize single color
const resultArray = daltonizeRGB(valuesArray, options);
return `rgb(${resultArray.join(', ')})`;
});
} else if (rgbaRegex.test(input)) {
resultString = input.replace(rgbaRegex, (match) => {
// split rgba() string into r, g, b, a integers
const valuesArray = match.split(',').map((value, i) => {
if (i == 0) {
value = value.substr(4)
}
return parseInt(value.trim(), 10)
}
);
// daltonize single color
const resultArray = daltonizeRGB(valuesArray.slice(0, 3), options);
return `rgba(${resultArray.join(', ')}, ${valuesArray[3]})`;
});
} else {
console.log(`invalid color type: ${input}`)
}
return resultString
}
function adjustImage(element, options) {
// edge case for document.body which does not have a class list
if (element.nodeType !== Node.ELEMENT_NODE) {
console.log("error: got element of node type " + element.nodeType)
return
}
// do not adjust images that have already been adjusted
if (element.hasAttribute('colorcue')) {
return
}
element.setAttribute('colorcue', true)
element.crossOrigin = "anonymous"; // THIS IS REQUIRED
element.onload = function () {
try {
daltonizeImage(element, {
type: options.type,
callback: function (processedCanvas) {
// Create a new Image element
let newImg = new Image();
newImg.crossOrigin = "anonymous";
newImg.src = processedCanvas.toDataURL();
newImg.alt = element.alt; // Copy alt text from original image
newImg.title = element.title; // Copy title from original image
newImg.className = element.className;
element.parentNode.replaceChild(newImg, element);
}
});
} catch (err) {
console.log(err);
console.log(element.src);
}
};
}
// ===== listen for message from popup or background script to apply changes
browser.runtime.onMessage.addListener(async (request) => {
console.log("got msg: " + request.action)
if ('action' in request && (request.action === 'enableFilter' || request.action === 'enableImageFilter')) {
location.reload()
}
});
// ===== apply filters on initial load
async function applyFilters() {
let storage = await browser.storage.local.get()
let isEnabled = storage.enabled
let isImagesEnabled = storage.images
if (isEnabled) {
let type = storage.result
options = { type: type };
adjustColors(document.body, options);
if (isImagesEnabled) {
var toReplace = Array.from(document.getElementsByTagName("img"));
toReplace.forEach((element) => { adjustImage(element, options) });
}
}
}
document.addEventListener('DOMContentLoaded', applyFilters())
// ===== setup mutation observer to adjust lazily loaded images
// TODO: may have to do this for single colors also?
const observer = new MutationObserver((records, observer) => {
records.forEach(async (record) => {
if (record.type == 'childList') {
const addedNodes = Array.from(record.addedNodes)
const lazyImages = addedNodes.reduce((acc, node) => {
// do not add TEXT_NODE's which are added on loading more images
if (node.nodeType === Node.ELEMENT_NODE) {
const imgElements = Array.from(node.querySelectorAll('img:not([colorcue])'));
return acc.concat(imgElements);
} else {
return acc
}
}, []);
if (lazyImages.length > 0) {
// process lazy loaded images
let storage = await browser.storage.local.get()
let isEnabled = storage.enabled
let isImagesEnabled = storage.images
if (isEnabled && isImagesEnabled) {
let type = storage.result
options = { type: type };
lazyImages.forEach((element) => {
adjustImage(element, options)
})
}
}
}
})
})
// prevent memory leaks by disconnecting observer
window.addEventListener('beforeunload', () => {
if (observer) {
observer.disconnect()
}
})
observer.observe(document.body, {
childList: true,
subtree: true
})