Search code examples
reactjsmathtransparencyopacity

Transparency to Opacity conversion


My question is mostly mathematical, but here some context: I have an HTML range input (basically a slider) representing the transparency of a map object (open layers) with percentage range from 0-100. My onChange function in javaScript should convert the percentage value to opacity, which ranges from 1-0.

These two ranges are indirectly proportional, meaning a transparency value of 0% should result in a opacity value of 1, while a transparency value of e.g. 70% should result in 0.3 opacity etc.

Transparency: [0...100]

Opacity: [1...0]

I am coding in react, so the opacity comes from the component state. The input value uses the opacity to calculate the transparency value, the onChange function recalculates the opacity from the transparency and sets the component state.

To show you give you an idea, here is some pseudo code:

<input
        type="range"
        min="0"
        max="100"
        rows="1"
        value={opacity =complicatedConversion=> transparency}
        onChange={e => {
          this.setState({opacity: transparency =complicatedConversion=> opacity});
        }}
      />

I need formulas that convert the range values to the corresponding one in the other range. I've tried to come up with a formula, but usually end up dividing by zero or resulting in an opacity greater than 1.

The easiest fix would be to just forget about the transparency and just use opacity, but my task requirements are strict and I think this type of formula could come in useful in other situations.

Are there any Math heads around that could give me a hint? Or does anyone know the formula for ranges like these?

Thanks a lot


Solution

  • The formula is

    opacity = 1 - (transparency/100)
    

    You can easily verify it works:

    • Transparency=0 leads to opacity=1
    • Transparency=100 leads to opacity=0
    • Transparency=50 leads to opacity=0.5