infodev
infodev

Reputation: 5235

Get colors values from percentages

I have to get color from a percentages between 0% and 200%.

Here's the gradient palette

Gradient

My actual algorithme is taking 5 colors gradients

percentageToColor(perc) {
  perc = Math.trunc(perc);
  perc > 200 ? (perc = 200) : '';
  const hue = 200 - perc;
  return `hsl(${hue}, 100%, 50%)`;

I don't see how to adapt it to get only 2 gradient colors ( same Blue from 0 to 100% ,then start adding red red, at 200% all red )

The best is that colors gradient to be generic , but specific blue and red is good too.

I don't find any library to make that.

Upvotes: 0

Views: 399

Answers (1)

Richard
Richard

Reputation: 7433

Calculate the red aspect and blue aspect of RGB based on the percentage you get, then insert them to your rgb value.

Here's a working example:

window.onload = function() {
  let colorShower = document.querySelector('.color-shower')
  let colorSlider = document.querySelector('#colorSlider')
  let blueAspect = percentage => Math.round(255 * (1 - (percentage - 1) / 200))
  let redAspect = percentage => Math.round(255 * (percentage - 1) / 200)
  let percentage = colorSlider.value
  let buildColor = (redAspect, blueAspect) => `rgb(${redAspect}, 0, ${blueAspect}`
    
  colorShower.style.backgroundColor = buildColor(redAspect(percentage), blueAspect(percentage))
  
  colorSlider.addEventListener('input', e => {
    percentage = colorSlider.value
    colorShower.style.backgroundColor = buildColor(redAspect(percentage), blueAspect(percentage))
  })
}
.color-shower {
  width: 100%;
  height: 50px;
}

.color-slider {
  width: 100%;
}
<div class = "color-shower"></div>
<input type = "range" min = "1" max = "200" value = "1" class = "color-slider" id = "colorSlider">

Upvotes: 1

Related Questions