xxxxxxxxxx
42
//________________________________________ STEP 1: HARD CODED TOGGLE BUTTON (P5)
//________________________________________ GLOBAL VARIABLES
//........................................ To hard code a button which we can toggle, we need a global variable to keep
//........................................ track of the button's state. A boolean is perfect for that.
let tog = false; //_______________________ ' = false ' can be omitted, and it will be assigned 'false' automatically.
function setup() { //_____________________ SETUP
//...................................... Inside 'setup' we set the values screen and preset values that don't change
//...................................... change throughout the sketch, such as the size of the text.
createCanvas(400, 400);
textSize(20);
print("this is the start of a tutorial see: http://kll.engineering-news.org/kllfusion01/articles.php?article_id=166");
}
function draw() { //______________________ DRAW
//...................................... 'draw' is where we draw the button on the screen. By default the it refreshes
//...................................... 60 frames per second. We also add a hover effect (a mouse over) by changing
//...................................... the color of the button border.
background(200, 200, 0);
if (tog) fill(0, 200, 0);
else fill(0, 0, 200);
if (mouseX > 100 && mouseX < 180 && mouseY > 100 && mouseY < 130) stroke(200, 0, 200);
else stroke(0, 200, 200);
strokeWeight(3);
rect(100, 100, 80, 30); //______________ button as rectangle
fill(200);
noStroke();
text("press", 110, 120); //_____________ text placed on top of the button
}
function mousePressed() { //______________ OPERATION
//...................................... The function 'mousePressed' gets executed each time the user clicks the mouse
//...................................... button. When that happens we could check if the mouse cursor is at the same
//...................................... location as the rectangle that we placed in 'draw'. If so, we switch the state
//...................................... of the global variable 'tog'.
if (mouseX > 100 && mouseX < 180 && mouseY > 100 && mouseY < 130) {
tog = !tog; //________________________ switch the button state from 'false' to 'true' or from 'true' to 'false'
print("button " + tog); //____________ optional logging
}
}