3

I am using a rgba mixin like rgba('#2f305a',0.8), which works well, but I want to take it a step further. I need to make the color after opacity to appear the same color as if it were solid. I thought I saw a function that did this a while back, but can't seem to find it. Is there one our there or does anyone have one? I tried converting this and did this:

@function alphaCalc($desiredColour, $desiredAlpha, $backgroundColour: white) {
    $r3: red($desiredColour);
    $g3: green($desiredColour);
    $b3: blue($desiredColour);

    $r2: red($backgroundColour);
    $g2: green($backgroundColour);
    $b2: blue($backgroundColour);

    $r1: ($r3 - $r2) / $desiredAlpha + $r2;
    $g1: ($g3 - $g2) / $desiredAlpha + $g2;
    $b1: ($b3 - $b2) / $desiredAlpha + $b2;

    @return rgba($r1, $g1, $b1, $desiredAlpha);
}

.someEl {
    background-color: alphaCalc(#2f305a,0.8);
}

Problem is I get an error: "$red: Color value -5 must be between 0 and 255 for 'rgba'"

r3 = 47; r2 = 255; r1 = (47-255)/0.8+255 = -5

So it seems like the formula is off or am I missing something here? Anybody have a solution?

Community
  • 1
  • 1
fanfavorite
  • 5,128
  • 1
  • 31
  • 58
  • To clarify: if you overlaid a semi-transparent red element over a blue element, you want the red element you want a value that's redder but still transparent or purple and opaque? – cimmanon Jun 20 '14 at 16:21
  • so if red is over blue, it would still look like the same red only with transparency. – fanfavorite Jun 20 '14 at 16:54
  • Try using the `abs()` function on the final result (eg. `abs($r1)`) and see if that gives you the desired effect. – cimmanon Jun 20 '14 at 17:24
  • Yeah I was playing with that and it appears to give the correct color, but it looks to have an opacity of 1 instead of what is given – fanfavorite Jun 20 '14 at 17:32
  • Actually it does, my mistake. Had a background on something I was testing. Thanks! – fanfavorite Jun 20 '14 at 17:37
  • If you post that answer, I'll mark it correct! – fanfavorite Jun 20 '14 at 17:38
  • Are you actually getting an exact match? I tried overlaying it with an opaque div of $desiredColour, and am seeing a small difference. – Kukosk Dec 10 '14 at 15:27

1 Answers1

0

To ensure that you're always working with positive numbers, you want to use the abs() function:

@return rgba(abs($r1), abs($g1), abs($b1), $desiredAlpha);
cimmanon
  • 67,211
  • 17
  • 165
  • 171