-2

i have set the background color #ec2024(red) with opacity of .5.

As I see using color picker, the color value slightly changed and becomes #F69092(pink)

How to get the output value #F69092(pink) from #ec2024 and .5 opacity value using js or jquery?

TIA

Beginner
  • 193
  • 1
  • 8
  • Basicly you cannot... The opacity CSS property sets the opacity of an element. Opacity is the degree to which content behind an element is hidden, and is the opposite of transparency. [Opacity](https://developer.mozilla.org/en-US/docs/Web/CSS/opacity). So a color with opacity that you try to "catch" will be a full color. and it wont have anymore opacity, if you try to mix color and opacity check out the subject as duplicate – MaxiGui Sep 07 '20 at 11:53
  • `Math.round((parseInt('ec2024', 16) * 0.5) + parseInt('ffffff', 16) * (1- 0.5)).toString(16)` – Endless Sep 07 '20 at 12:13

1 Answers1

-1

Take % of background color and mix them both. It is easy to write.

I did created very simple snippet that is showing how it works:

const mixColors = (c1, c2, p = 0.5) => {
  const pn = n => ('0' + n.toString(16)).slice(-2);
    const [r0, g0, b0, r1, g1, b1] = [
    parseInt(c1.slice(1, 3), 16),
    parseInt(c1.slice(3, 5), 16),
    parseInt(c1.slice(5, 7), 16),
    parseInt(c2.slice(1, 3), 16),
    parseInt(c2.slice(3, 5), 16),
    parseInt(c2.slice(5, 7), 16),
  ];
    const [r, g, b] = [
    Math.round(r0 * p + r1 * (1 - p)),
    Math.round(g0 * p + g1 * (1 - p)),
    Math.round(b0 * p + b1 * (1 - p)),
  ];
  return `#${pn(r)}${pn(g)}${pn(b)}`;
};

const setValue = val => {
  document.querySelector('.value').innerHTML = `${(val * 100).toFixed(0)}%`;
  document.querySelector('.mixed-color').value = mixColors(
    document.querySelector('.color2').value,
    document.querySelector('.color1').value,
    val
  );
};

document.querySelector('.range').addEventListener('input', function() {
  setValue(this.value);
});

setValue(0.5);
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  
  <div>
    <input class="color1" type="color" value="#F69092">
    <label for="head">Color 1</label>
  </div>
  
  <div>
    <input class="color2" type="color" value="#6699cc">
    <label for="head">Color 2</label>
  </div>
  
  <input class="range" type="range" min="0" max="1" step="0.01"/>
  <span class="value"></span>
  
  <div>
    <input class="mixed-color" type="color">
    <label for="head">Mixed Color</label>
  </div>
</body>
</html>
gkucmierz
  • 1,055
  • 1
  • 9
  • 26