Last active
May 31, 2017 01:01
-
-
Save Daniel-Hug/c3261f87c798b42adb3fa6317af138e6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// given an array of numbers scale each value so that | |
// the smallest is newMin and the largest is newMax | |
// while maintaining the ratio of distances between values | |
function stretchRange(nums, newMin, newMax) { | |
var min = Math.min.apply(Math, nums); | |
var max = Math.max.apply(Math, nums); | |
var range = max - min; | |
var newRange = newMax - newMin; | |
var scaled = []; | |
for (var i = 0; i < nums.length; i++) { | |
var fractionOfRange = (nums[i] - min) / range; | |
scaled.push(newMin + newRange * fractionOfRange); | |
} | |
return scaled; | |
} | |
// Pass a number and the range that this number falls in. | |
// Returns a CSS color string with a hue representing your number in your range. | |
function numToHue(num, min, max) { | |
var hue = Math.round(stretchRange([min || 0, num, max || 1], 0, 359)[1]); | |
var saturation = 43; | |
var lightness = 62; | |
return 'hsl(' + hue + ',' + saturation + '%,' + lightness + '%)'; | |
} | |
// Pass a number and the range that this number falls in. | |
// Returns a CSS color string with a shade from black to white representing your number in your range. | |
function numToShade(num, min, max) { | |
var rgb = Math.round(stretchRange([min || 0, num, max || 1], 0, 255)[1]); | |
return { | |
background: 'rgb(' + rgb + ',' + rgb + ',' + rgb + ')', | |
foreground: rgb > 255 / 2 ? 'black' : 'white' | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment