Open In App

Materials in WebGL and p5.js

In this article, we will learn how to apply different types of material in WebGL. Light reflects off objects differently depending on their angle of reflection as well as the material of the object. There are four types of materials in p5.js:

Example 1: Using the fill() method.






let angle = 0.3;
  
function setup() {
  createCanvas(600, 400, WEBGL);
}
  
function draw() {
    
  // Set the background
  background(250);
  
  fill(200,0,255);
    
  push();
    
  // Rotate on all three axis.
  rotateX(angle*0.3);
  rotateY(angle*0.6);
  rotateZ(angle*0.9);
    
  // Set the shape
  torus(150, 30);
   
  angle +=0.06;
  pop();
}

Output:



Example 2: Using the normalMaterial() method.




let angle = 0.3;
  
function setup() {
  createCanvas(600, 400, WEBGL);
}
  
function draw() {
    
  // Set the background
  background(250);
    
  // Set the material type.
  normalMaterial();
    
  push();
    
  // Rotate on all three axis.
  rotateX(angle*0.3);
  rotateY(angle*0.6);
  rotateZ(angle*0.9);
    
  // Set the shape
  torus(150, 30);
   
  angle +=0.06;
  pop();
}

Output:

Example 3: Using ambientMaterial() when there is no light.




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

Output:

Example 4: Using ambientMaterial() when there is light that is being reflected.




let angle = 0.3;
  
function setup() {
  createCanvas(600, 400, WEBGL);
}
  
function draw() {
    
  //set the  light 
  pointLight(0,0,255 ,200,-200,0)
    
  // Set the background
  background(250);
  
  // Set the material
  ambientMaterial(0,0,255);
  push();
    
  // Rotate on all three axis.
  rotateX(angle*0.3);
  rotateY(angle*0.6);
  rotateZ(angle*0.9);
    
  // Set the shape
  torus(150, 30);
   
  angle +=0.06;
  pop();
}

Output:

Example 4: Using specularMaterial() method.




let angle = 0.3;
  
function setup() {
  createCanvas(600, 400, WEBGL);
}
  
function draw() {
    
  // Set the  light 
  pointLight(255,255,0 ,200,-200,0)
    
  // Set the background
  background(250);
  
  // Set the material
  specularMaterial(250, 0, 0);
  push();
    
  // Rotate on all three axis.
  rotateX(angle*0.3);
  rotateY(angle*0.6);
  rotateZ(angle*0.9);
    
  //Set the shape
  torus(150, 30);
   
  angle +=0.06;
  pop();
}

Output:


Article Tags :