xxxxxxxxxx
75
// A demonstration of the p5js map function, which remaps one
// range to another—a very common task in graphics programming and beyond.
// In fact, Arduino has the same method.
//
// Here's p5js' map documentation:
// https://p5js.org/reference/#/p5/map
//
// Here's Arduinos':
// https://www.arduino.cc/reference/en/language/functions/math/map/
//
// Arduino's map function in C is literally just:
// long map(long x, long in_min, long in_max, long out_min, long out_max) {
// return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
// }
//
// By Professor Jon E. Froehlich
// @jonfroehlich
// http://makeabilitylab.io
//
let _sliderTop;
let _sliderBot;
let _randomizeButton;
function setup() {
createCanvas(500, 400);
_sliderTop = new Slider(40, 130, 200, 20, 0, 10, 5);
_sliderBot = new Slider(40, 200, 400, 20, 0, 100, 50);
_randomize = createButton("Randomize");
_randomize.mouseClicked(onRandomizeButton);
_randomize.position(40, 280);
let pDescription = createElement('p', 'The p5js <a href="https://p5js.org/reference/#/p5/map">map()</a>\
function allows us to easily map values in one range to another\
like with these two sliders. We are keeping them in sync by mapping the values\
from one range to another. Try it out!');
pDescription.style('color', '#111111');
pDescription.position(40, 0);
pDescription.size(400,50);
}
function draw() {
background(200);
_sliderTop.draw();
_sliderBot.draw();
}
function mouseDragged(){
if(_sliderTop.thumbState === SliderThumbState.GRABBED){
_sliderTop.setThumbPositionFromXPixelLocation(mouseX);
const sliderBotVal = map(_sliderTop.val, _sliderTop.minVal, _sliderTop.maxVal,
_sliderBot.minVal, _sliderBot.maxVal);
_sliderBot.val = sliderBotVal;
}else if(_sliderBot.thumbState === SliderThumbState.GRABBED){
_sliderBot.setThumbPositionFromXPixelLocation(mouseX);
const sliderTopVal = map(_sliderBot.val, _sliderBot.minVal, _sliderBot.maxVal,
_sliderTop.minVal, _sliderTop.maxVal);
_sliderTop.val = sliderTopVal;
}
}
function onRandomizeButton(){
_sliderTop.setValues(floor(random(0,6)), floor(random(8,21)), floor(random(5,8)));
_sliderBot.setValues(floor(random(0, 30)), floor(random(50, 300)), 30);
// initialize the bottom slider to the top slider's value so they are synchronized
const sliderBotVal = map(_sliderTop.val, _sliderTop.minVal, _sliderTop.maxVal,
_sliderBot.minVal, _sliderBot.maxVal);
_sliderBot.val = sliderBotVal;
}