How to create 3D Geometries in webGL and p5.js ?
Last Updated :
16 Jul, 2021
In this article, we will see how to draw 3D geometry (containing length, width, and height) in p5.js. The default rendering in p5.js is used for 2D images, and for the 3D images, we use WEBGL which enables 3D render by introducing the Z dimension to the geometry.
Syntax:
createCanvas( windowWidth, windowHeight, WEBGL )
Example 1: In this example, we will use webGL and p5.js to create a 3D geometry and rotate it in all directions.
Javascript
let angle = 0;
function setup() {
createCanvas(600, 600, WEBGL);
}
function draw() {
background(175);
ambientLight(255);
push();
translate(mouseX - width / 2,
mouseY - width / 2);
rotateX(angle);
rotateZ(angle * 0.03);
rotateY(angle * 0.06);
noStroke();
normalMaterial();
box(150, 150, 150);
push();
angle += .06
}
|
Output:
Example 2: In this example, we will use webGL and p5.js to create a 3D geometry using image as side of geometry and rotate it in all directions.
Javascript
let angle = 0;
function preload() {
img = loadImage( 'gfg.jpg' );
}
function setup() {
createCanvas(600, 600, WEBGL);
}
function draw() {
background(175);
ambientLight(255);
push();
translate(10, 10, 10);
rotateX(angle);
rotateZ(angle * 0.03);
rotateY(angle * 0.06);
noStroke();
normalMaterial();
texture(img);
box(150, 150, 150);
push();
angle += .06
}
|
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...