UNPKG

@hexorialstudio/color-blinder

Version:

Color Blinder Simulate color blindness of the given valid color hex code

83 lines (76 loc) 1.95 kB
/* * color-blinder * https://github.com/HexorialStudio/color-blinder * * see blinder.js for more information about the original source. * * Copyright (c) 2020 Hexorial Studio LLP * Licensed under the MIT license. */ "use strict"; var Blinder = require("./blinder.js").Blind; var colorVisionData = { protanomaly: { type: "protan", anomalize: true }, protanopia: { type: "protan" }, deuteranomaly: { type: "deutan", anomalize: true }, deuteranopia: { type: "deutan" }, tritanomaly: { type: "tritan", anomalize: true }, tritanopia: { type: "tritan" }, achromatomaly: { type: "achroma", anomalize: true }, achromatopsia: { type: "achroma" }, }; var hexToRgb = (hex) => { // Convert HEX value to RGB value const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); return result ? { r: parseInt(result[1], 16), g: parseInt(result[2], 16), b: parseInt(result[3], 16), } : null; }; const rgbToHex = (rgb) => { // Convert RGB value to Hex value if (!rgb || !rgb.r || !rgb.g || !rgb.b) { return "#000000"; } return `#${toHex(rgb.r)}${toHex(rgb.g)}${toHex(rgb.b)}`; }; const toHex = function (c) { // converts string to Hex var hex = parseInt(c).toString(16); return hex.length == 1 ? "0" + hex : hex; }; var createBlinder = function (key) { return function (colorString) { var color = hexToRgb(colorString); if (!color) { return "#000000"; } var rgb = new Blinder( { R: color.r, G: color.g, B: color.b, }, colorVisionData[key].type, colorVisionData[key].anomalize ); rgb.R = rgb.R || 0; rgb.G = rgb.G || 0; rgb.B = rgb.B || 0; delete rgb.X; delete rgb.Y; delete rgb.Z; return rgbToHex({ r: rgb.R, g: rgb.G, b: rgb.B, }); }; }; // add our exported functions for (var key in colorVisionData) { exports[key] = createBlinder(key); }