Skip to content
Related Articles

Related Articles

p5.js focused Variable
  • Last Updated : 08 Mar, 2021

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:

Javascript






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:

  • When the sketch is focused.

  • When the sketch is not focused.

Example 2:

Javascript




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:

  • When the sketch is focused.

  • When the sketch is not focused.

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

My Personal Notes arrow_drop_up
Recommended Articles
Page :