Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Average 2 hex colors together in javascript

Tags:

Alright thought I would throw this one out there for the crowd to think over.

Given a function (written in javascript) that expects two strings formated like a hex color (ex #FF0000)

return a hex color that is the average of both of the colors passed.

function averageColors(firstColor,secondColor)
{
  ...
  return avgColor;
}

--edit--

average would be defined as enter image description here

if the color passed was yellow and the second was light purple the returned color would be a medium orange

like image 969
samccone Avatar asked Jun 16 '11 04:06

samccone


People also ask

How many combinations of hex colors are there?

How Many Hex Colors Are There? In standard #RRGGBB notation, there are 256^3 color combinations available, or 16,777,216. This is because each color value RR, GG, BB can contain 256 different values, ranging from 00 to FF.

How many Web hex colors are there?

Shorthand hexadecimal form This shorthand form reduces the palette to 4,096 colors, equivalent of 12-bit color as opposed to 24-bit color using the whole six-digit form (16,777,216 colors).


2 Answers

I hate sounding like the oh-so-broken jQuery record, but there is a jQuery plugin for this already.

$.xcolor.average(color, color)

like image 112
Matt Ball Avatar answered Oct 01 '22 08:10

Matt Ball


A quick/dirty/convenient/ES6 way to blend two hex colors by a specified perecentage:

// blend two hex colors together by an amount
function blendColors(colorA, colorB, amount) {
  const [rA, gA, bA] = colorA.match(/\w\w/g).map((c) => parseInt(c, 16));
  const [rB, gB, bB] = colorB.match(/\w\w/g).map((c) => parseInt(c, 16));
  const r = Math.round(rA + (rB - rA) * amount).toString(16).padStart(2, '0');
  const g = Math.round(gA + (gB - gA) * amount).toString(16).padStart(2, '0');
  const b = Math.round(bA + (bB - bA) * amount).toString(16).padStart(2, '0');
  return '#' + r + g + b;
}

console.log(blendColors('#00FF66', '#443456', 0.5));

Where amount should be 0 to 1, with 0 being exactly colorA, 1 being exactly colorB, and 0.5 being the "midpoint".

like image 38
V. Rubinetti Avatar answered Oct 01 '22 08:10

V. Rubinetti