Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;


});
like image 716
William Avatar asked Sep 05 '25 19:09

William


1 Answers

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.

like image 200
Jim W says reinstate Monica Avatar answered Sep 08 '25 10:09

Jim W says reinstate Monica