Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
498 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

Edit: I've made this available as a Gist, so you don't have to look this up, in the future.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...