Skip to content

Instantly share code, notes, and snippets.

@paulkaplan
Last active September 14, 2020 13:44
Show Gist options
  • Save paulkaplan/6513707 to your computer and use it in GitHub Desktop.
Save paulkaplan/6513707 to your computer and use it in GitHub Desktop.
Create an ASCII STL file from a THREE.js mesh that can be saved save from browser and 3D printed
/*
Paul Kaplan, @ifitdidntwork
Create an ASCII STL file from a THREE.js mesh
that can be saved save from browser and 3D printed
--------------------------------------------------
See further explanation here:
http://buildaweso.me/project/2013/2/25/converting-threejs-objects-to-stl-files
--------------------------------------------------
Saving the file out of the browser is done using FileSaver.js
find that here: https://github.com/eligrey/FileSaver.js
*/
function stringifyVertex(vec){
return "vertex "+vec.x+" "+vec.y+" "+vec.z+" \n";
}
// Given a THREE.Geometry, create an STL string
function generateSTL(geometry){
var vertices = geometry.vertices;
var tris = geometry.faces;
var stl = "solid pixel\n";
for(var i = 0; i<tris.length; i++){
stl += ("facet normal "+stringifyVector( tris[i].normal )+" \n");
stl += ("outer loop \n");
stl += stringifyVertex( vertices[ tris[i].a ];
stl += stringifyVertex( vertices[ tris[i].b ];
stl += stringifyVertex( vertices[ tris[i].c ];
stl += ("endloop \n");
stl += ("endfacet \n");
}
stl += ("endsolid");
return stl
}
// Use FileSaver.js 'saveAs' function to save the string
function saveSTL( geometry, name ){
var stlString = generateSTL( geometry );
var blob = new Blob([stlString], {type: 'text/plain'});
saveAs(blob, name + '.stl');
}
@gamikun
Copy link

gamikun commented Sep 25, 2013

Hello, i think it's missing ")" after stringifyVertex calls in line 27, 28 and 28.

:)

@paulkaplan
Copy link
Author

Yup and another typo too, thanks!

@fakhrulhasan01
Copy link

How to use it. I mean, what will be values in parameters??

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment