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:
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:
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