Search code examples
javascriptmathcolorshsl

How to generate numbers within a range in a non random way with JavaScript?


I know how to generate a random number between two numbers. But what I'd like to achieve is a way to generate a number between two numbers in a not totally random way. Let me explain...

So I have a function that generates a color based on a number passed into it. If that number is between 0 and 600, I'd like it to pass a number between 0 and 120 to the hue of the hsl value. If the number is greater than 600, I'd like a number between 120 and 240 passed to the hue of the hsl value. My function looks something like this:

getColor:function (number {
  var hue;
  var color;
  if (number <= 600) {
    hue = [A number between 0 and 120];
  } else if (number >= 600) {
    hue = [A number between 120 and 240];
  }
  color = 'hsl(' + hue + ', 100%, 80%)'
  return color;
 }

So the higher the number passed into the function, for example, between 0 and 600, the higher the hue value between 0 and 120. That make sense?

Thx u -- Gaweyne


Solution

  • Simple Math:

    hue = Math.floor(number * 120 / 600);
    

    Or with both points:

    function transpose(smin, smax, dmin, dmax) {
        var slen = smax - smin;
        var dlen = dmax - dmin;
        var ratio = dlen / slen;
        return function(num) {
          return num * ratio + smin;
        }
    }
    
    transpose(0, 600, 0, 120)(300); // 60