Open In App

Lights in WebGL and p5.js

Last Updated : 17 Mar, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will learn how to apply different types of lights in p5.js. Lighting is a simple but powerful way to provide depth and realism in p5.js sketches. There are three types of lights available in p5.js:

  • Ambient Light: It is the simplest of the three lights. It provides even ambient lighting to objects drawn afterward. It takes a p5.Color object or RGB numerical values as parameters. It is defined using the ambientLight() method.
  • Directional Light: The rays of a directional light shine in a given direction without any specific point of origin. It cannot be positioned closer or farther away from any geometry. It is defined using the directionalLight() method.
  • Point Light: A point light takes a color and a location as parameters. It shines from a specific point of origin, and therefore reflects differently when it is farther or nearer an object. It is defined using the pointLight() method.

Example 1: Using the ambientLight() method to create an ambient light.

Javascript




let angle = 0.3;
  
function setup() {
  createCanvas(600, 400, WEBGL);
}
  
function draw() {
    
  // Set the blue light 
  ambientLight(0,0,255);
    
  // Set the background
  background(250);
  
  // Set the material
  ambientMaterial(255);
    
  // Rotate on all three axis.
  rotateX(angle*0.3);
  rotateY(angle*0.6);
  rotateZ(angle*0.9);
    
  // Set the shape
  sphere(150);
  
  angle +=0.06;
}


Output:

Example 2: Using the directionalLight() method to create a directional light.

Javascript




let angle = 0.3;
  
function setup() {
  createCanvas(600, 400, WEBGL);
}
  
function draw() {
  let dirY = (mouseY / height - 0.5) *2;
  let dirX = (mouseX / width - 0.5) *2;
  
  // Set the directional light 
  directionalLight(0, 0, 250, dirX, -dirY, 0.25);
    
  // Set the background
  background(250);
  
  // Set the material
  normalMaterial();
    
  // Rotate on all three axes
  rotateX(angle*0.3);
  rotateY(angle*0.6);
  rotateZ(angle*0.9);
    
  // Set the shape
  sphere(150);
   
  angle +=0.06;
}


Output:

Example 3: Using the pointLight() method to create a point light.

Javascript




let angle = 0.3;
  
function setup() {
  createCanvas(600, 400, WEBGL);
}
  
function draw() {
    
  // Set a point light in the given direction
  pointLight(0, 0, 255, mouseX - 200, mouseY - 200, 200);
    
  // Set the background
  background(250);
  
  // Set the material
  ambientMaterial(255);
    
  // Rotate on all three axes
  rotateX(angle*0.3);
  rotateY(angle*0.6);
  rotateZ(angle*0.9);
  noStroke();
    
  // Set the shape
  sphere(150);
    
  angle +=0.06;
}


Output:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads