I have this script that generates a random order for a group of numbers when the page is refreshed, and I would like to randomize the colors of the numbers (each number a different color) as well. It also could be that each number has a fixed color, and they just appear random by virtue of the numbers getting randomized. I can't figure out how to do that either. Any help is greatly appreciated.
var contents=new Array()
contents[0]='0'
contents[1]='1'
contents[2]='2'
contents[3]='3'
contents[4]='4'
contents[5]='5'
contents[6]='6'
contents[7]='7'
contents[8]='8'
contents[9]='9'
contents[10]='10'
contents[11]='11'
contents[12]='12'
contents[13]='13'
contents[14]='14'
contents[15]='15'
contents[16]='16'
contents[17]='17'
contents[18]='18'
contents[19]='19'
contents[20]='20'
var spacing="<br />"
var the_one
var z=0
while (z<contents.length){
the_one=Math.floor(Math.random()*contents.length)
if (contents[the_one]!="_selected!"){
document.write(contents[the_one]+spacing)
contents[the_one]="_selected!"
z++
}
}
Adjust with the following:
const c = [1,2,3].map(ele => Math.floor(Math.random() * 216));
document.write(`<span style="color: rgb(${c.join(",")});">${contents[the_one]+spacing}<span>`);
See example:
var contents = new Array()
contents[0] = '0'
contents[1] = '1'
contents[2] = '2'
contents[3] = '3'
contents[4] = '4'
contents[5] = '5'
contents[6] = '6'
contents[7] = '7'
contents[8] = '8'
contents[9] = '9'
contents[10] = '10'
contents[11] = '11'
contents[12] = '12'
contents[13] = '13'
contents[14] = '14'
contents[15] = '15'
contents[16] = '16'
contents[17] = '17'
contents[18] = '18'
contents[19] = '19'
contents[20] = '20'
var spacing = "<br />"
var the_one
var z = 0
while (z < contents.length) {
the_one = Math.floor(Math.random() * contents.length)
if (contents[the_one] != "_selected!") {
const c = [1,2,3].map(ele => Math.floor(Math.random() * 216));
document.write(`<span style="color: rgb(${c.join(",")});">${contents[the_one]+spacing}<span>`);
contents[the_one] = "_selected!"
z++
}
}
Edit: re-read the question and it had different needs. But I'll leave this answer here since it explains on how to get randomized colors (the actual topic) in JavaScript.
Here are the functions you'll need to create random hex color values:
const getRandomHex = () => Math.floor(Math.random() * 256).toString(16).padStart(2, '0');
const getRandomRGB = ({R = getRandomHex(), G = getRandomHex(), B = getRandomHex(), A } = {}) => ['#', R, G, B, A].join('');
console.log(getRandomRGB());
console.log(getRandomRGB({ A: '00' }));
The first function getRandomHex will convert random (0-255) numeric value as Base16 aka hexadecimal string. And if necessary, adds an additional zero in front.
The main function getRandomRGB will append three (red, green, blue) values to an array and then join the array as single string.
In addition, you can override R/G/B (and alpha channel) values as passed properties.
The reason I selected this approach is simply that it allows manipulating the generated R/G/B values if needed (like in use case: "keep the 'red value' static - while green and blue values are randomised").
Related
DESCRIPTION for a task:
One of the common ways of representing color is the RGB color model, in which the Red, Green, and Blue primary colors of light are added together in various ways to reproduce a broad array of colors.
One of the ways to determine brightness of a color is to find the value V of the alternative HSV (Hue, Saturation, Value) color model. Value is defined as the largest component of a color:
V = max(R,G,B)
You are given a list of colors in 6-digit hexidecimal notation #RRGGBB. Return the brightest of these colors!
For example,
brightest(["#001000", "#000000"]) == "#001000"
brightest(["#ABCDEF", "#123456"]) == "#ABCDEF"
If there are multiple brightest colors, return the first one:
brightest(["#00FF00", "#FFFF00", "#01130F"]) == "#00FF00"
Note that both input and output should use upper case for characters A, B, C, D, E, F.
My solution:
function brightest(colors){
let colorIndex = 0,
maxValue = 0
for (let i = 0; i < colors.lenght; i++) {
let color = colors[i],
r = ParseInt(color.slise(1,3), 16),
g = ParseInt(color.slise(3,5), 16),
b = ParseInt(color.slise(5,7), 16),
value = Math.max(r,g,b)
if (value > maxValue) {
maxValue = value
colorIndex = i
}
}
return colors [colorIndex]
}
Result:
Test failed with colors = #CAA365,#1861D3,#E8E2C6,#3D3548,#F19BBF,#BF12C3: expected '#CAA365' to deeply equal '#F19BBF'
What is wrong? And how can I fix this?
declare a variable
let value = Math.max(r,g,b)
length not lenght
let/var to variables
parseInt not ParseInt
slice not slise
And all will working
I have a homework to do, that is:
Pick a random color, from yellow, blue and red, given the probability of:
Yellow: 3/7
Blue: 1/7
Red: 3/7
I know that I could work this around by using something like:
[yellow, yellow, yellow, blue, red, red, red]
But I don't think this would be programatically good, since when I chance the probability, I would have to change the array.
So, I thought I could try something like a weight approach
let yellow_probability = 3/7
let blue_probability = 1/7
let red_probability = 3/7
const colors = ['yellow', 'blue', 'red']
function pickPosition(yellow_probability, blue_probability, red_probability){
let yellow_weight = Math.random() * yellow_probability
let blue_weight = Math.random() * blue_probability
let red_weight = Math.random() * red_probability
let weights = [yellow_weight, blue_weight, red_weight]
let max_of_array = Math.max.apply(Math, weights);
pickedColor = weights.indexOf(max_of_array)
return pickedColor
}
pickedColorIndex = pickPosition(yellow_probability, blue_probability, red_probability)
pickedColor = colors[pickedColorIndex]
console.log(pickedColor)
I did a test:
let n=1000000;
let yellow=0, blue=0, red=0;
for (let i=0; i<n; i++) {
pickedColorIndex = pickPosition(yellow_probability, blue_probability, red_probability)
if (pickedColorIndex==0) yellow++
else if (pickedColorIndex==1) blue++
else red++;
}
console.log("yellow = " + yellow/n );
console.log("blue = " + blue/n );
console.log("red = " + red/n );
And I would expect this test to output something like:
Yellow = 0.43
Blue = 0.14
Red = 0.43
But I am getting:
Yellow = 0.48
Blue = 0.03
Red = 0.48
It is interesting to point out that the code works when the probabilities are equal (1/3, 1/3, 1/3) or something like (1/2, 1/2, 0)
Can anyone point out what I am doing wrong?
Instead of a single random value, you create as many as different items you have and later take the one with the max value.
This promotes values/items with a higher factor/probability.
Instead of this approach, you could take a single random value and take all probabilities into an array and check in which interval the random value is. Take this item.
EDIT: The code
function getRandomIndex(probabilities) {
var random = Math.random(),
i;
for (i = 0; i < probabilities.length; i++) {
if (random < probabilities[i]) return i;
random -= probabilities[i];
}
return probabilites.length - 1;
}
var probabilities = [3 / 7, 1 / 7, 3 / 7],
j = 1e6,
count = [0, 0, 0];
while (j--) count[getRandomIndex(probabilities)]++;
console.log(count);
This is similar to the approach mentioned in the duplicate. You create an array with ratios same as the probabilities. (Here I'm using 2 decimal places and adding ~100 items to the array. You could add multiply by a bigger number and have .toFixed(3) for better accuracy)
function getRandomWithProbability(array) {
const filled = array.flatMap(([color, prob]) => {
const length = prob.toFixed(2) * 100;
return Array.from({ length }).fill(color)
});
const random = Math.floor(Math.random() * filled.length);
return filled[random]
}
const arr = [["yellow", 3/7], ["blue", 1/7], ["red", 3/7]]
console.log(getRandomWithProbability(arr))
This question already has answers here:
Extract list of supported HTML or X11 colour names and their RGB values using javascript
(2 answers)
Closed last year.
Is there a way to programmatically generate a list of all named CSS colors supported by the browser via JavaScript? (.e.g. Red, Green, AliceBlue etc.)
Note: I'm not asking for a pre-compiled list, I'm looking for something more akin to document.body.style, which returns an object with all css properties supported by the browser.
I guess the closed you can get is starting from a pre-compiled color name list and check if the browser supports the color. You can assign the color with
div.stlye.backgroundColor = '';
div.style.backgroundColor = potentialColor;
and retrieve the actual color information with
var actualColorString = window.getComputedStyle(div).background;
If the assigned color is not valid (or black), the color string starts with
rgba(0, 0, 0, 0)
Otherwise it is a known css color name.
Here is some jsfiddle to demonstrate the color check:
https://jsfiddle.net/tc8f5pgy/4/
I used this method to create a Color enum for my project:
https://github.com/stefaneidelloth/treezjs/blob/master/src/components/color/color.js
And here is part of the code as a backup for the jsfiddle:
<div id='color-element'></div>
//source of color names: https://simple.wikipedia.org/wiki/List_of_colors
const colorNames = [
'Amaranth',
//...
];
//another source of color names: https://gist.github.com/bobspace/2712980
const cssColorNames = [
"AliceBlue",
"AntiqueWhite",
//...
];
//another source of color names: https://chir.ag/projects/ntc/ntc.js
var extendedColors = [
["000000", "Black"],
["000080", "Navy Blue"],
//...
];
function camelize(str) { //source: https://stackoverflow.com
/questions/2970525/converting-any-string-into-camel-case
var camelString= str.replace(/(?:^\w|[A-Z]|\b\w)/g, function(word, index) {
return index === 0 ? word.toLowerCase() : word.toUpperCase();
}).replace(/\s+/g, '');
return camelString.replace(/\//g,'').replace(/-/g,'').replace(/'/g,'');
}
function rgba2hex(orig) { //source: https://stackoverflow.com/questions/49974145/how-to-convert-rgba-to-hex-color-code-using-javascript
var a, isPercent,
rgb = orig.replace(/\s/g, '').match(/^rgba?\((\d+),(\d+),(\d+),?([^,\s)]+)?/i),
alpha = (rgb && rgb[4] || "").trim(),
hex = rgb ?
(rgb[1] | 1 << 8).toString(16).slice(1) +
(rgb[2] | 1 << 8).toString(16).slice(1) +
(rgb[3] | 1 << 8).toString(16).slice(1) : orig;
if (alpha !== "") {
a = alpha;
} else {
a = 01;
}
// multiply before convert to HEX
a = ((a * 255) | 1 << 8).toString(16).slice(1)
hex = hex + a;
return hex;
}
function handleActualColor(name, rgbaColorString){
var hexColorString = rgba2hex(rgbaColorString);
var output = "Color." + name + " = new Color('"+ name +"','#"+ hexColorString + "');"
console.log(output);
}
var potentialColorSet = new Set();
for(var colorName of colorNames){
potentialColorSet.add(camelize(colorName));
}
for(var colorName of cssColorNames){
potentialColorSet.add(camelize(colorName));
}
for(var entry of extendedColors){
var colorName = entry[1];
potentialColorSet.add(camelize(colorName));
}
var potentialColors = Array.from(potentialColorSet).sort();
var div = document.getElementById('color-element');
for(var potentialColor of potentialColors){
div.style.backgroundColor = '';
div.style.backgroundColor = potentialColor;
var actualColorString = window.getComputedStyle(div).background;
var endIndex = actualColorString.indexOf(')');
var rgbaColorString = actualColorString.substring(0, endIndex+1);
if(rgbaColorString !== 'rgba(0, 0, 0, 0)'){
handleActualColor(potentialColor, rgbaColorString);
if(potentialColor == 'screaminGreen'){
throw new Error('foo');
}
}
if(potentialColor.toLowerCase() === 'black'){
handleActualColor(potentialColor, rgbaColorString);
}
}
I came up with this list of colors you might use for TEXT or Backgrounds
Just call them by names i.e: <div class="black_bg silver_text"></div>
.black_text{color:#000000;}.black_bg{background-color:#000000;}
.silver_text{color:#c0c0c0;}.silver_bg{background-color:#c0c0c0;}
.gray_text{color:#808080;}.gray_bg{background-color:#808080;}
.white_text{color:#ffffff;}.white_bg{background-color:#ffffff;}
.maroon_text{color:#800000;}.maroon_bg{background-color:#800000;}
.red_text{color:#ff0000;}.red_bg{background-color:#ff0000;}
.purple_text{color:#800080;}.purple_bg{background-color:#800080;}
.fuchsia_text{color:#ff00ff;}.fuchsia_bg{background-color:#ff00ff;}
.green_text{color:#008000;}.green_bg{background-color:#008000;}
.lime_text{color:#00ff00;}.lime_bg{background-color:#00ff00;}
.olive_text{color:#808000;}.olive_bg{background-color:#808000;}
.yellow_text{color:#ffff00;}.yellow_bg{background-color:#ffff00;}
.navy_text{color:#000080;}.navy_bg{background-color:#000080;}
.blue_text{color:#0000ff;}.blue_bg{background-color:#0000ff;}
.teal_text{color:#008080;}.teal_bg{background-color:#008080;}
.aqua_text{color:#00ffff;}.aqua_bg{background-color:#00ffff;}
.orange_text{color:#ffa500;}.orange_bg{background-color:#ffa500;}
.aliceblue_text{color:#f0f8ff;}.aliceblue_bg{background-color:#f0f8ff;}
.antiquewhite_text{color:#faebd7;}.antiquewhite_bg{background-color:#faebd7;}
.aquamarine_text{color:#7fffd4;}.aquamarine_bg{background-color:#7fffd4;}
.azure_text{color:#f0ffff;}.azure_bg{background-color:#f0ffff;}
.beige_text{color:#f5f5dc;}.beige_bg{background-color:#f5f5dc;}
.bisque_text{color:#ffe4c4;}.bisque_bg{background-color:#ffe4c4;}
.blanchedalmond_text{color:#ffebcd;}.blanchedalmond_bg{background-color:#ffebcd;}
.blueviolet_text{color:#8a2be2;}.blueviolet_bg{background-color:#8a2be2;}
.brown_text{color:#a52a2a;}.brown_bg{background-color:#a52a2a;}
.burlywood_text{color:#deb887;}.burlywood_bg{background-color:#deb887;}
.cadetblue_text{color:#5f9ea0;}.cadetblue_bg{background-color:#5f9ea0;}
.chartreuse_text{color:#7fff00;}.chartreuse_bg{background-color:#7fff00;}
.chocolate_text{color:#d2691e;}.chocolate_bg{background-color:#d2691e;}
.coral_text{color:#ff7f50;}.coral_bg{background-color:#ff7f50;}
.cornflowerblue_text{color:#6495ed;}.cornflowerblue_bg{background-color:#6495ed;}
.cornsilk_text{color:#fff8dc;}.cornsilk_bg{background-color:#fff8dc;}
.crimson_text{color:#dc143c;}.crimson_bg{background-color:#dc143c;}
.darkblue_text{color:#00008b;}.darkblue_bg{background-color:#00008b;}
.darkcyan_text{color:#008b8b;}.darkcyan_bg{background-color:#008b8b;}
.darkgoldenrod_text{color:#b8860b;}.darkgoldenrod_bg{background-color:#b8860b;}
.darkgray_text{color:#a9a9a9;}.darkgray_bg{background-color:#a9a9a9;}
.darkgreen_text{color:#006400;}.darkgreen_bg{background-color:#006400;}
.darkgrey_text{color:#a9a9a9;}.darkgrey_bg{background-color:#a9a9a9;}
.darkkhaki_text{color:#bdb76b;}.darkkhaki_bg{background-color:#bdb76b;}
.darkmagenta_text{color:#8b008b;}.darkmagenta_bg{background-color:#8b008b;}
.darkolivegreen_text{color:#556b2f;}.darkolivegreen_bg{background-color:#556b2f;}
.darkorange_text{color:#ff8c00;}.darkorange_bg{background-color:#ff8c00;}
.darkorchid_text{color:#9932cc;}.darkorchid_bg{background-color:#9932cc;}
.darkred_text{color:#8b0000;}.darkred_bg{background-color:#8b0000;}
.darksalmon_text{color:#e9967a;}.darksalmon_bg{background-color:#e9967a;}
.darkseagreen_text{color:#8fbc8f;}.darkseagreen_bg{background-color:#8fbc8f;}
.darkslateblue_text{color:#483d8b;}.darkslateblue_bg{background-color:#483d8b;}
.darkslategray_text{color:#2f4f4f;}.darkslategray_bg{background-color:#2f4f4f;}
.darkslategrey_text{color:#2f4f4f;}.darkslategrey_bg{background-color:#2f4f4f;}
.darkturquoise_text{color:#00ced1;}.darkturquoise_bg{background-color:#00ced1;}
.darkviolet_text{color:#9400d3;}.darkviolet_bg{background-color:#9400d3;}
.deeppink_text{color:#ff1493;}.deeppink_bg{background-color:#ff1493;}
.deepskyblue_text{color:#00bfff;}.deepskyblue_bg{background-color:#00bfff;}
.dimgray_text{color:#696969;}.dimgray_bg{background-color:#696969;}
.dimgrey_text{color:#696969;}.dimgrey_bg{background-color:#696969;}
.dodgerblue_text{color:#1e90ff;}.dodgerblue_bg{background-color:#1e90ff;}
.firebrick_text{color:#b22222;}.firebrick_bg{background-color:#b22222;}
.floralwhite_text{color:#fffaf0;}.floralwhite_bg{background-color:#fffaf0;}
.forestgreen_text{color:#228b22;}.forestgreen_bg{background-color:#228b22;}
.gainsboro_text{color:#dcdcdc;}.gainsboro_bg{background-color:#dcdcdc;}
.ghostwhite_text{color:#f8f8ff;}.ghostwhite_bg{background-color:#f8f8ff;}
.gold_text{color:#ffd700;}.gold_bg{background-color:#ffd700;}
.goldenrod_text{color:#daa520;}.goldenrod_bg{background-color:#daa520;}
.greenyellow_text{color:#adff2f;}.greenyellow_bg{background-color:#adff2f;}
.grey_text{color:#808080;}.grey_bg{background-color:#808080;}
.honeydew_text{color:#f0fff0;}.honeydew_bg{background-color:#f0fff0;}
.hotpink_text{color:#ff69b4;}.hotpink_bg{background-color:#ff69b4;}
.indianred_text{color:#cd5c5c;}.indianred_bg{background-color:#cd5c5c;}
.indigo_text{color:#4b0082;}.indigo_bg{background-color:#4b0082;}
.ivory_text{color:#fffff0;}.ivory_bg{background-color:#fffff0;}
.khaki_text{color:#f0e68c;}.khaki_bg{background-color:#f0e68c;}
.lavender_text{color:#e6e6fa;}.lavender_bg{background-color:#e6e6fa;}
.lavenderblush_text{color:#fff0f5;}.lavenderblush_bg{background-color:#fff0f5;}
.lawngreen_text{color:#7cfc00;}.lawngreen_bg{background-color:#7cfc00;}
.lemonchiffon_text{color:#fffacd;}.lemonchiffon_bg{background-color:#fffacd;}
.lightblue_text{color:#add8e6;}.lightblue_bg{background-color:#add8e6;}
.lightcoral_text{color:#f08080;}.lightcoral_bg{background-color:#f08080;}
.lightcyan_text{color:#e0ffff;}.lightcyan_bg{background-color:#e0ffff;}
I want create a array from array by random, but I'm starting on javascript. Here is my question.
//array
var t = ["house","pen","table","eletronic"];
//-> selected a name option 0
var w = t[0]; // selected
var x = w;
var y = 0 to 3; // random
var house =["red","blue","orange","black"];
var pen =["silver", "gold", "cooper","plastic"];
var table =["marble","oak","yep","pine"];
var eletro=["computer","mobile","mac","tablet"];
// what i wish
var z = house[0]; // return red // x = typeof return object
//x this is the error type string not recognize list array query
var z = x[y]; // x = typeof return string
var z = "house"[0]; // return h - return string - not object
//after make a default
var a = x[y]; //y != y
var b = x[y]; //y != y
document.getElementById("demo1").innerHTML=z; // blue house;
document.getElementById("demo2").innerHTML=a; // silver pen;
document.getElementById("demo3").innerHTML=b; // marble table;
<p id "demo1"></p>
<p id "demo2"></p>
<p id "demo3"></p>
I think I must convert double quotes - "house" - string to object - house - to convert to a var and before feed the system?
I'm not 100% sure what you're asking here, but the behaviour i believe you want can be accomplished using 2d arrays as such -
const t = [["red","blue","orange","black"], ["silver", "gold", "cooper","plastic"], ["marble","oak","yep","pine"], ["computer","mobile","mac","tablet"]]
const [rand1, rand2] = [Math.floor(Math.random() * t.length), Math.floor(Math.random() * t[0].length)]
console.log(t[rand1][rand2])
It's not quite clear to me if this is what you're looking for, but one solution might be to structure your data so that it's easier to get at:
const items = {
house: ["red","blue","orange","black"],
pen: ["silver", "gold", "cooper","plastic"],
table: ["marble","oak","yep","pine"],
eletro: ["computer","mobile","mac","tablet"]
}
const randomChoice = list => list[Math.floor(list.length * Math.random())]
const randomObject = (items) => {
const itemType = randomChoice(Object.keys(items))
const modifier = randomChoice(items[itemType])
return `${modifier} ${itemType}`
}
randomObject(items) //=> "marble table" or "plastic pen", etc.
Update
The comment asked to pick a random element of a certain type. This variation would allow for that:
const randomOfType = (items, itemType) => {
const modifier = randomChoice(items[itemType])
return `${modifier} ${itemType}`
}
const randomObject = (items) => randomOfType(items, randomChoice(Object.keys(items)))
randomOfType(items, 'table') //=> "oak table" or "marble table", etc.
You could use the eval() function to obtain the object reference, but it could lead to hairy problems so it would better use another option like for example a switch statement:
//array
var t = ["house","pen","table","electronic"];
var house = ["red","blue","orange","black"];
var pen = ["silver", "gold", "cooper","plastic"];
var table = ["marble","oak","yep","pine"];
var electronic = ["computer","mobile","mac","tablet"];
var w = Math.floor(Math.random() * 3); // random type index (0 to 3)
var x = t[w]; // name of the random type
var y = Math.floor(Math.random() * 3); // random option (0 to 3)
switch (w) { // use the appropriate object based on type index
case 0: z=house[y]; break;
case 1: z=pen[y]; break;
case 2: z=table[y]; break;
case 3: z=electronic[y]; break;
}
console.log(w, z);
var z = z + ' ' + x // appending "house" to color
console.log(z);
document.getElementById("demo1").innerHTML=z;
<p id="demo1"></p>
<p id="demo2"></p>
<p id="demo3"></p>
I have some code which takes strings representing hexadecimal numbers - hex colors, actually - and adds them. For example, adding aaaaaa and 010101 gives the output ababab.
However, my method seems unnecessarily long and complicated:
var hexValue = "aaaaaa";
hexValue = "0x" + hexValue;
hexValue = parseInt(hexValue, 16);
hexValue = hexValue + 0x010101;
hexValue = hexValue.toString(16);
document.write(hexValue); // outputs 'ababab'
The hex value is still a string after concatenating 0x, so then I have to change it to a number, then I can add, and then I have to change it back into hex format! There are even more steps if the number I'm adding to it is a hexadecimal string to begin with, or if you take into consideration that I am removing the # from the hex color before all this starts.
Surely there's a simpler way to do such simple hexadecimal calculations! And just to be clear, I don't mean just putting it all on one line like (parseInt("0x"+"aaaaaa",16)+0x010101).toString(16) or using shorthand - I mean actually doing less operations.
Is there some way to get javascript to stop using decimal for all of its mathematical operations and use hex instead? Or is there some other method of making JS work with hex more easily?
No, there is no way to tell the JavaScript language to use hex integer format instead of decimal by default. Your code is about as concise as it gets but note that you do not need to prepend the "0x" base indicator when you use "parseInt" with a base.
Here is how I would approach your problem:
function addHexColor(c1, c2) {
var hexStr = (parseInt(c1, 16) + parseInt(c2, 16)).toString(16);
while (hexStr.length < 6) { hexStr = '0' + hexStr; } // Zero pad.
return hexStr;
}
addHexColor('aaaaaa', '010101'); // => 'ababab'
addHexColor('010101', '010101'); // => '020202'
As mentioned by a commenter, the above solution is chock full of problems, so below is a function that does proper input validation and adds color channels separately while checking for overflow.
function addHexColor2(c1, c2) {
const octetsRegex = /^([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i
const m1 = c1.match(octetsRegex)
const m2 = c2.match(octetsRegex)
if (!m1 || !m2) {
throw new Error(`invalid hex color triplet(s): ${c1} / ${c2}`)
}
return [1, 2, 3].map(i => {
const sum = parseInt(m1[i], 16) + parseInt(m2[i], 16)
if (sum > 0xff) {
throw new Error(`octet ${i} overflow: ${m1[i]}+${m2[i]}=${sum.toString(16)}`)
}
return sum.toString(16).padStart(2, '0')
}).join('')
}
addHexColor2('aaaaaa', 'bogus!') // => Error: invalid hex color triplet(s): aaaaaa / bogus!
addHexColor2('aaaaaa', '606060') // => Error: octet 1 overflow: aa+60=10a
How about this:
var hexValue = "aaaaaa";
hexValue = (parseInt(hexValue, 16) + 0x010101).toString(16);
document.writeln(hexValue); // outputs 'ababab'
There is no need to add the 0x prefix if you use parseInt.
I think accepted answer is wrong. Hexadecimal color representation is not a linear. But instead, 3 sets of two characters are given to R, G & B.
So you can't just add a whole number and expect to RGB to add up correctly.
For Example
n1 = '005500'; <--- green
n2 = '00ff00'; <--- brighter green
Adding these numbers should result in a greener green.
In no way, adding greens should increase RED to increase. but by doing what accepted answer is doing, as in just treat whole number as one number then you'd carry over for numbers adding upto greater than f, f+1 = 10.
you get `015400` so by adding greens the RED increased .... WRONG
adding 005500 + 00ff00 should result in, = 00ff00. You can't add more green to max green.
For folks looking for a function that can add and subtract HEX colors without going out of bounds on an individual tuple, I wrote this function a few minutes ago to do just that:
export function shiftColor(base, change, direction) {
const colorRegEx = /^\#?[A-Fa-f0-9]{6}$/;
// Missing parameter(s)
if (!base || !change) {
return '000000';
}
// Invalid parameter(s)
if (!base.match(colorRegEx) || !change.match(colorRegEx)) {
return '000000';
}
// Remove any '#'s
base = base.replace(/\#/g, '');
change = change.replace(/\#/g, '');
// Build new color
let newColor = '';
for (let i = 0; i < 3; i++) {
const basePiece = parseInt(base.substring(i * 2, i * 2 + 2), 16);
const changePiece = parseInt(change.substring(i * 2, i * 2 + 2), 16);
let newPiece = '';
if (direction === 'add') {
newPiece = (basePiece + changePiece);
newPiece = newPiece > 255 ? 255 : newPiece;
}
if (direction === 'sub') {
newPiece = (basePiece - changePiece);
newPiece = newPiece < 0 ? 0 : newPiece;
}
newPiece = newPiece.toString(16);
newPiece = newPiece.length < 2 ? '0' + newPiece : newPiece;
newColor += newPiece;
}
return newColor;
}
You pass your base color as parameter 1, your change as parameter 2, and then 'add' or 'sub' as the last parameter depending on your intent.