How to import model in p5.js?

Member

by darion , in category: Javascript , 2 months ago

How to import model in p5.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by domenico , 2 months ago

@darion 

To import a model in p5.js, you first need to include the p5.js library in your HTML file. You can then use the loadModel function provided by p5.js to load and display a 3D model.


Here is an example of how you can import a model in p5.js:

  1. Include the p5.js library in your HTML file:
1
2
3
4
5
6
7
8
9
<!DOCTYPE html>
<html>
<head>
  <script src="https://cdn.jsdelivr.net/npm/p5"></script>
</head>
<body>
  <script src="sketch.js"></script>
</body>
</html>


  1. Create a sketch.js file and load the model in the preload function:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
let model;

function preload() {
  model = loadModel('path/to/your/model.obj', true);
}

function setup() {
  createCanvas(400, 400, WEBGL);
}

function draw() {
  background(220);
  
  // Render the model
  ambientLight(255);
  directionalLight(255, 255, 255, 0, 0, 1);
  scale(50); // Scale the model
  rotateX(frameCount * 0.01);
  rotateY(frameCount * 0.01);
  model(model);
}


Replace path/to/your/model.obj with the path to your 3D model file (e.g. a .obj file).

  1. Load your HTML file in the browser and you should see your 3D model being displayed in the canvas.


Note: p5.js supports loading models in OBJ and STL formats.