Last active
March 13, 2019 12:48
-
-
Save peeke/f7542d36d225a47ba7dda7ce501f539b to your computer and use it in GitHub Desktop.
Method to map a number from an input domain to an output range. Useful for animations based on userinput.
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
// This clamp function does not need left to be smaller than right, making it better suited for animations | |
const clamp = (input, left, right) => { | |
if (left > right) { | |
[left, right] = [right, left] | |
} | |
return Math.min(Math.max(input, left), right) | |
} | |
export default clamp |
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
const lerp = (a, b, weight) => a + weight * (b - a) | |
export default lerp |
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
import clamp from 'clamp' | |
import lerp from 'linear-interpolate' | |
const mapNumber = (input, inFrom, inTo, outFrom, outTo) => { | |
input = clamp(input, inFrom, inTo) | |
const t = (input - inFrom) / (inTo - inFrom) | |
return lerp(outFrom, outTo, t) | |
} | |
export default mapNumber | |
// mapNumber(1, 0, 10, 10, 30) outputs 12 | |
// mapNumber(5, 0, 10, 10, 30) outputs 20 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment