Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Pure SASS script for calculating the needed alpha channel of a top color to result in a target color on top of a specified bottom color.
@function calculateAlpha($topColor, $bottomColor, $targetColor) {
$topRgb: red($topColor), green($topColor), blue($topColor);
$bottomRgb: red($bottomColor), green($bottomColor), blue($bottomColor);
$targetRgb: red($targetColor), green($targetColor), blue($targetColor);
$alphaAvg: 0;
@for $i from 1 through 3 {
$alphaAvg: ($alphaAvg * ($i - 1) + (nth($targetRgb, $i) - nth($bottomRgb, $i)) / (nth($topRgb, $i) - nth($bottomRgb, $i))) / $i;
}
@return $alphaAvg;
}
@function calculateTopColor($alpha, $bottomColor, $targetColor) {
$topRgb: ();
$bottomRgb: red($bottomColor), green($bottomColor), blue($bottomColor);
$targetRgb: red($targetColor), green($targetColor), blue($targetColor);
@for $i from 1 through 3 {
$topRgb: append($topRgb, (nth($targetRgb, $i) - (1 - $alpha) * nth($bottomRgb, $i)) / $alpha);
}
@return rgb(nth($topRgb, 1), nth($topRgb, 2), nth($topRgb, 3));
}
.elem1 {
opacity: calculateAlpha(#000, #5e534f, #16110e);
background: calculateTopColor(0.8, #947e70, #7a7572);
}
// Above results in:
body {
opacity: 0.79464;
background: #737272;
}

A pure SASS-script to calculate what alpha channel that is needed for a color to achieve a certain target color when rendered on top of a specified bottom color.

This can be useful when extracting colors from a flat image where you can estimate two colors that are rendered on top of another, but need help with figuring out the alpha number of the top color to achieve the target color in the image.

Imagine eg. a sligthly transparent black box on top of an image. By color picking to adjacent pixels on the corner of the box – the one outside the box as the bottom color and the one in the box as the target color – and then specifying the top color as black and putting all of thos colors into this function – then you'll get back the approximate alpha color needed to achieve the wanted result.

Update 1: Addaded a function for also calculating what color to use to achieve a specific target color when the alpha channel is known (perhaps you have calculated the alpha for an adjacent element and want to figure out what color to use to get the most matching result)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment