我正在尝试重新创建Javascript中处理中使用的map function。 它永远不会崩溃,我只是输出不好。
下面你会找到我正在使用的功能。我完全被困在这里,所以任何帮助都会非常感激。
前两行特别是在任何数字超出函数范围的情况下。
function map(number, loworig, highorig, lowconversion, highconversion)
{
if (number < loworig) number = loworig;
else if (number > highorig) number = highorig;
var num = highorig-loworig;
var newnum = number-num;
var ratio = newnum/num;
var convnum = highconversion - lowconversion;
var newconv = convnum*ratio;
var result = newconv + convnum;
return result;
}
编辑:我只是回顾了我的代码,我做了一些硬编码的数字转换,让它在工作的时候运行。基本上,我的猜测并不是这个功能是正确的,但我似乎无法弄清楚为什么它不起作用。
答案 0 :(得分:3)
来自source code(对评论进行小规模重新格式化):
/**
* Re-maps a number from one range to another. In the example above,
* the number '25' is converted from a value in the range 0..100 into
* a value that ranges from the left edge (0) to the right edge (width)
* of the screen.
*
* Numbers outside the range are not clamped to 0 and 1, because
* out-of-range values are often intentional and useful.
*/
static public final float map(float value,
float start1, float stop1,
float start2, float stop2) {
return start2 + (stop2 - start2) * ((value - start1) / (stop1 - start1));
}
转换为JavaScript:
function map(value, start1, stop1, start2, stop2) {
return start2 + (stop2 - start2) * ((value - start1) / (stop1 - start1));
}