Javascript / jQuery - map a range of numbers to another range of numbers

后端 未结 8 1480

In other programming languages such as processing, there is a function which allows you to convert a number that falls within a range of numbers into a number within a diffe

8条回答
  •  既然无缘
    2020-12-02 17:56

    If your range always starts from 0 then all you have to do is

    mouseValue * range.max / screen.max
    

    A more involved any-range to any-range conversion would require

    function convertToRange(value, srcRange, dstRange){
      // value is outside source range return
      if (value < srcRange[0] || value > srcRange[1]){
        return NaN; 
      }
    
      var srcMax = srcRange[1] - srcRange[0],
          dstMax = dstRange[1] - dstRange[0],
          adjValue = value - srcRange[0];
    
      return (adjValue * dstMax / srcMax) + dstRange[0];
    
    }
    

    Use like convertToRange(20,[10,50],[5,10]);

提交回复
热议问题