0

Let's say I have 2 colors: a solid background color (6-digit hex value) and an overlay color with opacity (6-digit hex value and some opacity percentage).

What is a function for getting the effective resultant color (6-digit hex value)? In other words, if I paint both colors over the same area (background first, then overlay) and then use a dropper tool to get the color value, how can I programmatically get the same color value?

Any programming language (even pseudocode) is fine here.

sunw
  • 535
  • 5
  • 29
  • https://stackoverflow.com/questions/6735470/get-pixel-color-from-canvas-on-mouseover – Katie.Sun Nov 20 '18 at 00:44
  • Thank you @Katie.Sun -- however I'm looking for something different. I need a function that takes two overlapping colors (and opacity of top color) as arguments and produce the resulting effective solid color. The "dropper tool" example I gave was simply used to make my problem more clear -- that's not the intended final implementation. – sunw Nov 20 '18 at 02:50

2 Answers2

1

You need alpha compositing formula:

result_red =  fg_red * α_fg + bg_red * (1 - α_fg)
result_blue =  fg_blue * α_fg + bg_blue * (1 - α_fg)
result_green =  fg_green * α_fg + bg_green * (1 - α_fg)

You can found more information and examples in W3C Candidate Recommendation

raven cler
  • 36
  • 3
0

RGB color codes (and hex) have three different parts - values for red, green, and blue. To find the 'sum' of two colors, you would need to calculate the average of each part individually and then put them back together. Here's some JavaScript that takes two colors that have been split into numerical arrays, averages their values, and returns a new array. This would work for RGBA as well.

function calcColorAverages(firstColor, secondColor){

  let newColor = [];

  for(let index in firstColor){
    let colorOne = firstColor[index]
    let colorTwo = secondColor[index]

    let average = Math.round((colorOne + colorTwo) / 2);

    newColor[index] = average;

  }

  return newColor

}

let red = [255, 0, 0]
let blue = [0, 0, 255]

let purple = calcColorAverages(red, blue)

console.log(purple) //128, 0, 128
Katie.Sun
  • 711
  • 3
  • 15