In order to be able to get the sketch to respond to a key being pressed, I first have to click on the square. Nothing works until I do that. Does anyone have an idea of why that is?
let color = 180;
function setup() {
colorMode(HSB);
}
function draw() {
fill(color, 255, 255);
rect(25, 25, 50, 50);
}
function keyTyped() {
if (key === 'q') {
color = 0;
} else if (key === 'w') {
color = 20;
} else if (key === 'e') {
color = 40;
} else if (key === 'r') {
color = 60;
} else if (key === 't') {
color = 80;
} else if (key === 'y') {
color = 100;
}
return false; // this line prevents any default behaviour
}
Guessing that openprocessing is a browser environment like the Web Editor, which shows similar behaviour. It’s because another part of the browser is selected/focused (might have a specific name, not sure). It’s the same the other way around: after clicking on square and pressing buttons, these characters won’t be added to your text editor hence leaving your code intact.
In my case, keyTyped() works right after I click at the play icon.
Only when I click somewhere else, or return from another browser tab, I’d need to click at the square, or within 25 pixels far from it, to regain focus.
That focus regaining is needed b/c most code webhosters like:
And the size of that <iframe> is what actually determines the focus zone for our code.
In the online sketch “Damper Balls” below:
all the balls horizontally follow the mouse as long as the mouse pointer is within the canvas zone, b/c its <iframe> is exactly the same size of that sketch’s <canvas> element.