Open In App

p5.js focused Variable

The focused variable in p5.js is used to check whether the current window or sketch is in focus or not. When the sketch is in focus, the focused variable will have a true value, else it would be false. It is similar to the focus property in CSS. In p5.js, this variable only gives information about the main window or sketch. If the user changes the tab or clicks on an inspection window, it sets the variable to false.

Syntax:



focused

Below programs illustrate the focused variable in p5.js:

Example 1:






let img;
  
function preload(){
  img = loadImage("gfg.png");
}
  
function setup() {
  createCanvas(400, 400);
}
  
function draw() {
  background('green');
  
  image(img, width/2 - img.width/2,
        height/2 - img.height/2);
  
  // Check if the sketch is currently
  // not focused
  if (!focused) {
    
      // Draw lines if the sketch 
    // is not focused
    stroke(200, 0, 0);
    line(0, 0, height, height);
    line(height, 0, 0, height);
  }
}

Output:

Example 2:




let cylinder;
function preload() {
  
  // Load the model
  cylinder = loadModel('/cylinder.stl', true);
}
  
function setup() {
  
  createCanvas(400, 400, WEBGL);
}
  
function draw() {
  background('green');
  
  // Rotate the model
  rotateX(90);
    
  // Check if the sketch is
  // not focused
  if (!focused) {
      
    // Use stroke of red color
    stroke(200, 0, 0);
  } else {
    // Else use stroke of black color
    stroke(0);
  }
  
  // Display the model
  model(cylinder);
}

Output:

Reference:https://p5js.org/reference/#/p5/focused


Article Tags :