Monday, November 18, 2024
Google search engine
HomeLanguagesJavascriptp5.js lights() Function

p5.js lights() Function

The lights() function in p5.js is used to set the default ambient and directional light in the scene. The default ambient light used is ambientLight(128, 128, 128) and the directional light is directionalLight(128, 128, 128, 0, 0, -1). This function can be used to quickly add default lights in the scene.
The lights() function has to be used in the draw() function of the code to remain persistent in the scene.
Syntax: 
 

lights()

Parameters: This function does not accept any parameters.
Below examples illustrate the lights() function in p5.js:
Example 1:
 

javascript




let newFont;
let lightsEnable = false;
  
function preload() {
  newFont = loadFont('fonts/Montserrat.otf');
}
  
function setup() {
  createCanvas(600, 300, WEBGL);
  textFont(newFont, 18);
  
  lightsEnableCheck = createCheckbox(
      "Enable Default Lights", false);
  lightsEnableCheck.position(20, 60);
  
  // Toggle default light
  lightsEnableCheck.changed(() => {
    lightsEnable = !lightsEnable;
  });
}
  
function draw() {
  background("green");
  text("Click on the checkbox to toggle the"
     + " default lights.", -285, -125);
  noStroke();
  shininess(15);
  specularMaterial(250);
  
  if (lightsEnable) {
  
    // Enable the default lights
    lights();
  }
  
  sphere(80);
}


Output: 
 

lights-sphere

Example 2:
 

javascript




let newFont;
let lightsEnable = false;
  
function preload() {
  newFont = loadFont('fonts/Montserrat.otf');
}
  
function setup() {
  createCanvas(600, 300, WEBGL);
  textFont(newFont, 18);
  
  lightsEnableCheck = createCheckbox(
       "Enable Default Lights", false);
  
  lightsEnableCheck.position(20, 60);
  
  // Toggle default light
  lightsEnableCheck.changed(() => {
    lightsEnable = !lightsEnable;
  });
}
  
function draw() {
  background("green");
  text("Click on the checkbox to toggle the"
       + " default lights.", -285, -125);
  noStroke();
  shininess(15);
  specularMaterial(250);
  
  if (lightsEnable) {
  
    // Enable the default lights
    lights();
  }
  
  rotateX(millis() / 1000);
  rotateY(millis() / 1000);
  box(100);
}


Output: 
 

lights-box

Online editor: https://editor.p5js.org/
Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/
Reference: https://p5js.org/reference/#/p5/lights
 

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments