Lights in WebGL and p5.js
Last Updated :
17 Mar, 2021
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() {
ambientLight(0,0,255);
background(250);
ambientMaterial(255);
rotateX(angle*0.3);
rotateY(angle*0.6);
rotateZ(angle*0.9);
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;
directionalLight(0, 0, 250, dirX, -dirY, 0.25);
background(250);
normalMaterial();
rotateX(angle*0.3);
rotateY(angle*0.6);
rotateZ(angle*0.9);
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() {
pointLight(0, 0, 255, mouseX - 200, mouseY - 200, 200);
background(250);
ambientMaterial(255);
rotateX(angle*0.3);
rotateY(angle*0.6);
rotateZ(angle*0.9);
noStroke();
sphere(150);
angle +=0.06;
}
|
Output:
Share your thoughts in the comments
Please Login to comment...