How to export a 3D GGB model to use in p5.js
Introduction
I recently discovered that I can create a 3D model in GeoGebra to use it in the JavaScript library p5.js.
Step 1: Export your 3D object from GeoGebra
First we need to have a 3D object.
I use for example this one: https://www.geogebra.org/m/uz3ukzsf
We need to open it with the online app. On the top-right corner, click on the three dots menu and then select Open in App
Next, we need to export it. So click on the three bars menu on the top-right corner and select Download as... and then select 3D print (.stl)
On the pop-up window, select the option Filled Solid and click on Download
On the new pop-up window, change the name of the file (if you want) and click on Export
Step 2: Convert STL to OBJ
Since p5.js uses 3D models with extension OBJ, we need to convert our 3D GeoGebra model.
There are many free websites that you can use to convert STL files to OBJ files. For example:
https://products.aspose.app/3d/conversion/stl-to-obj
https://www.meshconvert.com/
Once we converted our file we can use it in p5.js.
Step 3: Upload 3D model to p5.js sketch
The easiest way to render our 3D GeoGebra object is using the online editor of p5.js:
https://editor.p5js.org/
Once it is open, click on the > arrow button (below the Play button) to show the files on the left-side column:
- sketch.js
- index.html
- style.css
Click on the button next to the title Sketch files to select Upload file
Select your file, or drag-&-drop it into to the pop-up window. It takes a few seconds to upload. Also, make sure your file is less than 5 megabytes.
Step 4: Rendering in p5.js sketch
Now you will need to replace the predefined code with the following:
let obj;
function preload() {
obj = loadModel('model.obj');
}
function setup() {
createCanvas(windowWidth, windowHeight, WEBGL);
}
function draw() {
background(0);
let s = 0.005;
rotateZ(frameCount * s);
rotateX(frameCount * s);
rotateY(frameCount * s);
scale(width * 0.008); // Scaled to make model fit into canvas
let locX = mouseX - height / 2;
let locY = mouseY - width / 2;
normalMaterial(); // For effect
model(obj);
}
Result
Final comments
If you are not familiar with p5.js, don't worry there are plenty of online tutorials on the web. I personally recommend the Coding Train.
If you are a p5.js user already, then I hope you find this useful. Send me a tweet to share what you have created: @jcponcemath
You can see the final result in the live demo here:
https://editor.p5js.org/jcponce/sketches/i9mb1GAmv
Enjoy!