Reputation:
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
Upvotes: 0
Views: 152
Reputation: 14992
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
Upvotes: 2
Reputation: 959
Ok first of all you should know the maximum and minimum values of number
. In my example The maximum value of number will be 1200 and the minimum 0, so the range is between 0 and 1200. And the range of hue
is between 0 and 240.
the higher the number
passed into the function, the higher the hue
value.
0 hue
= 0 number
;
120 hue
= 600 number
;
240 hue
= 1200 number
;
=> 1 hue
= (600 / 120) number
= (1200 / 240) number
=> 1 hue
= 5 number
In my example, (with number
between 0 and 1200 and 600 is the middle) 1 value in hue
is equal to 5 value in number
. So :
hue = number / 5;
if you want hue to be an integer just use Math
:
hue = Math.floor(number / 5);
In my example hue
will grow up by 1 every time you add 5 to number
, it doesn't matter if number
is less or more than 600 because the range of number
on both sides of 600 is the same (600 is in the middle of the range). In case this is not what you want, and 600 is not in the middle of the range, you will have to do the same calculation above twice.
var max = [maximum value of number];
var min = [minimum value of number];
getColor:function (number {
var hue;
var color;
if (number <= 600) {
hue = Math.floor( number / ((600 - min) / 120) );
} else if (number >= 600) {
hue = Math.floor( number / ((max - 600) / 120) ) + 120;
}
color = 'hsl(' + hue + ', 100%, 80%)';
return color;
}
Upvotes: 0