William
William

Reputation: 4588

How to scale any number range to between a value of 0 and 1 in JavaScript

I'm doing this little experiment with the web audio API and I want the vertical axis to affect the gain value of the oscillator (see fiddle below). I need to scale the value between the top of the canvas to the bottom of the canvas to between a value of 0 and 1 so the mousemove events on the Y axis affect the gain audibly. I figure this is a general math question that could be applied to any range of numbers but I just don't know how to do it.

http://jsfiddle.net/63Y54/

var audioContext = new webkitAudioContext();



oscillator = undefined ;

$("#myCanvas").mousedown(function() {
    var osc = audioContext.createOscillator(); 
    gainNode = audioContext.createGainNode();
    oscillator = osc;
    oscillator.start(0);

});


$("#myCanvas").mouseup(function() {
    oscillator.stop();
});



$("#myCanvas").mousemove(function(event) {
    console.log(event.pageX);
    console.log(event.pageY);
    oscillator.type = "sawtooth";
    gainNode.gain.value = (event.pageX);
    oscillator.connect(gainNode); 
    gainNode.connect(audioContext.destination); 
    oscillator.frequency.value = event.pageX;


});

Upvotes: 4

Views: 4148

Answers (2)

Jim W
Jim W

Reputation: 5016

You divide your value by the maximum value possible.

Let's say your value is 50 and the range of values is 0 to 100, then 50/100 = 0.5.

Similarly if your value is 0, then 0/100=0.

If you value is 100, then 100/100=1.

Upvotes: 5

Gaurav Karwal
Gaurav Karwal

Reputation: 116

Lets say the width of the screen is w and height is h.

Your answer:

currentXPosition/w currentYPosition/h

You can round it based on your requirement. For Y you may need to negate it as Y Pos are negative i.e. -(currentYPosition/h)

Upvotes: 0

Related Questions