How to convert RGB24 to RGB for web? - javascript

I have some colors in RGB24 format, for example: 1581613
How to convert it to RGB for web usage?
If I understand correctly, the format is as follows RRRGGBB.
Last code i've trying to run is:
const color = 1581613;
const red = (color >> 5) * 255 / 7;
const green = ((color >> 2) & 0x07) * 255 / 7;
const blue = (color & 0x03) * 255 / 3;
But my attempts did not lead to success.

I'm guessing a lot here, but here goes:
const color = 1581613;
const red = (color >> 16) & 255;
const green = (color >> 8) & 255;
const blue = color & 255;
const hex = red.toString(16) + green.toString(16) + blue.toString(16);
document.write(JSON.stringify({rgb: [red, green, blue], hex }, null, 2));

Related

javascript - Mix three colors by percentage

In my javascript application I have to mix three colors red, yellow and green. I have to mix them by percentage specified for each color something like:
mixColours(redColor, yellowColor, greenColor, redPercentage, yellowPercentage, greenPercentage)
I have found this solution on SO, but this only works for two colors.
Is it possible to achieve the mix of three colors? If yes, can anybody share some piece of code, please?
Extract colors
round the final color
const mixColours = (color1, color2, color3, percentage1, percentage2, percentage3) => {
const red1 = parseInt(color1.slice(1, 3), 16);
const green1 = parseInt(color1.slice(3, 5), 16);
const blue1 = parseInt(color1.slice(5, 7), 16);
const red2 = parseInt(color2.slice(1, 3), 16);
const green2 = parseInt(color2.slice(3, 5), 16);
const blue2 = parseInt(color2.slice(5, 7), 16);
const red3 = parseInt(color3.slice(1, 3), 16);
const green3 = parseInt(color3.slice(3, 5), 16);
const blue3 = parseInt(color3.slice(5, 7), 16);
const red = Math.round((red1 * percentage1 + red2 * percentage2 + red3 * percentage3) / (percentage1 + percentage2 + percentage3));
const green = Math.round((green1 * percentage1 + green2 * percentage2 + green3 * percentage3) / (percentage1 + percentage2 + percentage3));
const blue = Math.round((blue1 * percentage1 + blue2 * percentage2 + blue3 * percentage3) / (percentage1 + percentage2 + percentage3));
return generateHex(red, green, blue);
};
Hope it helps

How for entered color calculate background color?

In my #vue/cli 4.1.1 app user enter color and I have to output
color value with entered color and I wonder how can I calculate and set background color
to be sure that entered color value is good visible. I mean if user entered white color(or near)
background must be dark?
Thanks
You can give an invert color - 255-color for each of rgb
function bg(r, g, b) {return [255-r, 255-g, 255-b]}
if you get it in hex format, you can convert it to rgb, then get the invert. like so:
function invert(hex){
hex = parseInt(hex.substring(1), 16);
var r = hex >> 16;
hex -= r << 16;
var g = hex >> 8;
hex -= g << 8;
var b = hex;
return `rgb(${255-r},${255-g},${255-b})`;
}
var color1 = "#eeff00";
var color2 = "#22faef";
var color3 = "#f1f1f1";
document.querySelector('#a').style = `color:${color1};background-color:${invert(color1)}`;
document.querySelector('#b').style = `color:${color2};background-color:${invert(color2)}`;
document.querySelector('#c').style = `color:${color3};background-color:${invert(color3)}`;
div {
padding: 10px;
}
<div id="a">Hello world!</div>
<div id="b">Hello world!</div>
<div id="c">Hello world!</div>
You can determine the entered color to be light or dark on the basis of its luminance.
Here you can find a formula it's calculated on.
So, you can, for example, define the function isLight like this
function isLight(color) {
// Converting hex color to rgb
const [red, green, blue] = hexToRgb(color);
// Determine luminance
const luminance = (0.299 * red + 0.587 * green + 0.114 * blue)/255;
// Returning true if color is light
return luminance > 0.5;
}
// function for converting hex colors to rgb array format
function hexToRgb(hex) {
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? [
parseInt(result[1], 16),
parseInt(result[2], 16),
parseInt(result[3], 16)
] : null;
}
By using this function you can determine if the user color is light or dark and thus set the appropriate background

Check if Gradient is too light javascript

I'm trying to add a gradient to every element to each page, for now, I've achieved it but I've run into a problem.
If the gradient is too light my text is not visible, is there any way to check if the gradient color is too light and then change the text to black?
Here is my code
This is the gradients element = https://github.com/ghosh/uiGradients/blob/master/gradients.json
const cards = document.querySelectorAll('.card');
cards.forEach((card)=>{
let i = Math.floor(Math.random() * gradients.length);
const color = gradients[i].colors;
color.forEach((color)=> {
let finalGradient = `background: linear-gradient(to right, ${color}, ${color}, ${color}) !important;`;
card.style.cssText = finalGradient;
})
})
Here a function that I use to detect if a color is light or dark. You can use it and adapt to your code:
function isLightOrDark(color) {
// Variables for red, green, blue values
var r, g, b, hsp;
// Check the format of the color, HEX or RGB?
if (color.match(/^rgb/)) {
// If HEX --> store the red, green, blue values in separate variables
color = color.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+(?:\.\d+)?))?\)$/);
r = color[1];
g = color[2];
b = color[3];
}
else {
// If RGB --> Convert it to HEX: http://gist.github.com/983661
color = +("0x" + color.slice(1).replace(
color.length < 5 && /./g, '$&$&'));
r = color >> 16;
g = color >> 8 & 255;
b = color & 255;
}
// HSP (Highly Sensitive Poo) equation from http://alienryderflex.com/hsp.html
hsp = Math.sqrt(
0.299 * (r * r) +
0.587 * (g * g) +
0.114 * (b * b)
);
// Using the HSP value, determine whether the color is light or dark
if (hsp>127.5) {
return 'light';
}
else {
return 'dark';
}
}

Lighten hex code in javascript [duplicate]

This question already has answers here:
Programmatically Lighten or Darken a hex color (or rgb, and blend colors)
(21 answers)
Closed 9 years ago.
I want to have the user be able to enter a random hex color and my javascript code would print out a lighter version of that color (some sort of algorithm so to speak)
A quick example of how I want the colors to change.
What the user inputs: #2AC0A3
What it spits out: #C6EEE6
Thanks so much to anyone who can help!
An easy way to lighten up a color is linear interpolation with white. In the same way, a color can be darkened by interpolating with black.
Here's a function that takes a color string and changes the brightness indicated by light:
function hex2(c) {
c = Math.round(c);
if (c < 0) c = 0;
if (c > 255) c = 255;
var s = c.toString(16);
if (s.length < 2) s = "0" + s;
return s;
}
function color(r, g, b) {
return "#" + hex2(r) + hex2(g) + hex2(b);
}
function shade(col, light) {
// TODO: Assert that col is good and that -1 < light < 1
var r = parseInt(col.substr(1, 2), 16);
var g = parseInt(col.substr(3, 2), 16);
var b = parseInt(col.substr(5, 2), 16);
if (light < 0) {
r = (1 + light) * r;
g = (1 + light) * g;
b = (1 + light) * b;
} else {
r = (1 - light) * r + light * 255;
g = (1 - light) * g + light * 255;
b = (1 - light) * b + light * 255;
}
return color(r, g, b);
}
When light is negative, the color is darkened; -1 always yields black. When light is positive, the color is lightened, 1always yields white. Finally, 0 always yields the original color:
alert(shade("#2ac0a3", 0.731));

Calculate color HEX having 2 colors and percent/position

Is it possible to calculate a color in a middle of a gradient?
var color1 = 'FF0000';
var color2 = '00FF00';
// 50% between the two colors, should return '808000'
var middle = gradient(color1, color2, 0.5);
I only have two hex strings, and I want one in return.
This should work:
It basically involves converting them to decimal, finding the halves, converting the results back to hex and then concatenating them.
var color1 = 'FF0000';
var color2 = '00FF00';
var ratio = 0.5;
var hex = function(x) {
x = x.toString(16);
return (x.length == 1) ? '0' + x : x;
};
var r = Math.ceil(parseInt(color1.substring(0,2), 16) * ratio + parseInt(color2.substring(0,2), 16) * (1-ratio));
var g = Math.ceil(parseInt(color1.substring(2,4), 16) * ratio + parseInt(color2.substring(2,4), 16) * (1-ratio));
var b = Math.ceil(parseInt(color1.substring(4,6), 16) * ratio + parseInt(color2.substring(4,6), 16) * (1-ratio));
var middle = hex(r) + hex(g) + hex(b);
An ES6 version with comprehensions:
function interpolateColor(c0, c1, f){
c0 = c0.match(/.{1,2}/g).map((oct)=>parseInt(oct, 16) * (1-f))
c1 = c1.match(/.{1,2}/g).map((oct)=>parseInt(oct, 16) * f)
let ci = [0,1,2].map(i => Math.min(Math.round(c0[i]+c1[i]), 255))
return ci.reduce((a,v) => ((a << 8) + v), 0).toString(16).padStart(6, "0")
}
As in the accepted answer, c0,c1 are color codes (without the leading #) and f is "progress" between the two values. (At f=0 this ends up returning c0, at f=1 this returns c1).
The first two lines convert the color codes into arrays of scaled integers
The third line:
"zips" the two integer arrays
sums the corresponding values
rounds the sum and clamps it to 0-255
The fourth line:
converts the integer array into a single integer (reduce and bitshifting)
converts the integer into its hexadecimal string form
ensures the resulting string is 6 characters long and returns it
I can't comment on the answer above, so I write it here:
I found out that in the Javascript substring method the to parameter index is not included in the returned string. That means:
var string = "test";
//index: 0123
alert(string.substring(1,3));
//will alert es and NOT est
Edit: So it should be:
parseInt(color1.substring(0,2), 16);
parseInt(color1.substring(2,4), 16);
and
parseInt(color1.substring(4,6), 16);
You can use this ready function (ES6):
const calculateMiddleColor = ({
color1 = 'FF0000',
color2 = '00FF00',
ratio,
}) => {
const hex = (color) => {
const colorString = color.toString(16);
return colorString.length === 1 ? `0${colorString}` : colorString;
};
const r = Math.ceil(
parseInt(color2.substring(0, 2), 16) * ratio
+ parseInt(color1.substring(0, 2), 16) * (1 - ratio),
);
const g = Math.ceil(
parseInt(color2.substring(2, 4), 16) * ratio
+ parseInt(color1.substring(2, 4), 16) * (1 - ratio),
);
const b = Math.ceil(
parseInt(color2.substring(4, 6), 16) * ratio
+ parseInt(color1.substring(4, 6), 16) * (1 - ratio),
);
return hex(r) + hex(g) + hex(b);
};
//////////////////////////////////////////////////////////////////////
console.log(calculateMiddleColor({ ratio: 0 / 5 })); // ff0000
console.log(calculateMiddleColor({ ratio: 5 / 5 })); // 00ff00
console.log(calculateMiddleColor({ ratio: 2.5 / 5 })); // 808000
console.log(calculateMiddleColor({ ratio: 4.2 / 5 })); // 29d700

Categories

Resources