53

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 different range. What I want to do is convert the mouse's X coordinate into a range between, say, 0 and 15. So the browser's window dimensions, while different for every user, might be, say, 1394px wide, and the current X coordinate might be 563px, and I want to convert that to the range of 0 to 15.

I'm hoping to find a function of jquery and javascript that has this ability built in. I can figure out the math to do this by myself, but I'd rather do this in a more concise and dynamic way.

I'm already capturing the screen dimensions and mouse dimensions with this code:

var $window = $(window);
var $document = $(document);


$document.ready(function() {
    var mouseX, mouseY; //capture current mouse coordinates
    var screenW, screenH; //capture the current width and height of the window
    var maxMove = 10;
    windowSize();

    $document.mousemove( function(e) {
        mouseX = e.pageX; 
        mouseY = e.pageY;

    });

    $window.resize(function() {
        windowSize();
    });

    function windowSize(){
        screenW = $window.width();
        screenH = $window.height();
    }

});

Thanks for any help you can provide.

1
  • 2
    I don't understand the question or is it just a rule of three ? May 25, 2012 at 14:37

10 Answers 10

165

You can implement this as a pure Javascript function:

function scale (number, inMin, inMax, outMin, outMax) {
    return (number - inMin) * (outMax - outMin) / (inMax - inMin) + outMin;
}

Use the function, like this:

const num = 5;
console.log(scale(num, 0, 10, -50, 50)); // 0
console.log(scale(num, -20, 0, -100, 100)); // 150

I'm using scale for the function name, because map is frequently associated with iterating over arrays and objects.

2
  • 1
    min: Number.prototype.map=function(a,b,c,d){return c+(d-c)*((this-a)/(b-a))}; Sep 23, 2014 at 18:37
  • 1
    const map = (num, in_min, in_max, out_min, out_max) => (num - in_min) * (out_max - out_min) / (in_max - in_min) + out_min Should be included to use ES6 syntax. Jun 23, 2018 at 17:38
9

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]);

1
  • Great! +1 but " if value < OR > " should return min value (dstRange[0]) OR maximum value (dstRange[1]).... Aug 31, 2013 at 23:34
4

For a general purpose mapping function, which is what the OP asked for, go here:

http://rosettacode.org/wiki/Map_range#JavaScript

2
1

This is simple math.

var screenWidth = $(window).width();
var mousePosition = e.pageX;
var max = 15;
var value = (mousePosition / screenWidth) * max;

Note that this can return a decimal number; if you don't want that, you can use Math.round on the result.

Live example

1
function proportion(value,max,minrange,maxrange) {
    return Math.round(((max-value)/(max))*(maxrange-minrange))+minrange;
}

In your case, use this as proportion(screencoord,screensize,0,15)

You'd also presumably want to get the Client size, not the screen size, as the Screen size refers to the maximum dimensions of the monitor, and not all users maximise their screen.

1

Let's say you have 6 variables :

  • minRange (0 in your example)
  • maxRange (15 in your example)
  • x
  • y
  • browserWidth
  • browserHeight

To have the range :

interval = maxRange - minRange;
rangeX = interval * x / browserWidth + minRange
rangeY = interval * y / browserHeight + minRange
1

well its simple math. well you have two ranges range1 = [a1,a2] and range2 = [b1,b2] and you want to map a value s in range one to a value t in range two. so this is the formula. t = b1 + (s-a1)*(b2-b1)/(a2-a1) in js it will be.

var mapRange = function(from, to, s) {
  return to[0] + (s - from[0]) * (to[1] - to[0]) / (from[1] - from[0]);
};

var range = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
for (var i = 0; i < range.length; i++) {
  range[i] = mapRange([0, 10], [-1, 0], range[i]);
}

console.log(range);
1

Floats should be always calculated.

function scale(
    srcNum: number,
    src: [start: number, end: number],
    dst: [start: number, end: number]
): number {
    return ((srcNum - src[0]) * (dst[1] - dst[0])) / (src[1] - src[0]) + dst[0];
}

scale(1, [0, 10], [0, 255]);   // 25.5
scale(1.5, [0, 10], [0, 255]); // 38.25
scale(2, [0, 10], [0, 255]);   // 51

Integers, an effective way is to create a mapping, so no more calculations are needed. But it really depends on the size of src range. For large range scale(...) should be more efective.

function createScale(
    src: [start: number, end: number],
    dst: [start: number, end: number]
): Record<number, number> {
    const map: Record<number, number> = {};
    for (let i = src[0]; i <= src[1]; i++) {
        map[i] = ((i - src[0]) * (dst[1] - dst[0])) / (src[1] - src[0]) + dst[0];
    }
    return map;
}

createScale([0, 10], [0, 255]);
// {
//     "1": 25.5,
//     "2": 51,
//     "3": 76.5,
//     "4": 102,
//     "5": 127.5,
//     "6": 153,
//     "7": 178.5,
//     "8": 204,
//     "9": 229.5,
//     "10": 255
// }
0

I've taken August Miller's idea and added limits to them (value can't go outside the range of in_min and in_max and if it does it returns out_min and out_max respectively) and minified it for those who want a copy paste function for their scripts:

function map(n,i,o,r,t){return i>o?i>n?(n-i)*(t-r)/(o-i)+r:r:o>i?o>n?(n-i)*(t-r)/(o-i)+r:t:void 0}

params are like map(value, in_min, in_max, out_in, out_max)

1
  • I like this because it's unreadable, but it doesn't seem to respect in_min. If I do map(8, 10,20, 40,50) it results in "38". The in_max works though. Using it anyway. Thanks. Jan 30, 2020 at 17:31
-1
Number.prototype.map = function (inMin, inMax, outMin, outMax) {
    return (this - inMin) / (inMax - inMin) * (outMax - outMin) + outMin;
}

(3).map(0,10,0,100);   // 30
(5).map(-10,10,0,200); // 150

it's "Map Range Unclamped", Returns Value mapped from one range into another. (e.g. 20 normalized from the range 10->50 to 20->40 would result in 25).

"Unclamped" means the number can exceed the range.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.