0

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

1
  • Transparency is in percent. To convert percent to numerical value you divide by 100. 100%/100 = 1, 30%/100 = 0.3. But this is transparency, you want the opposite, opacity. 1 - transparency number = opacity number.
    – Drew Reese
    Mar 31, 2020 at 18:18

1 Answer 1

1

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
1
  • Strikingly obvious. Thanks a lot
    – danji_ma90
    Mar 31, 2020 at 18:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.