Is there a way to get the dimensions (height, width, length) of an stl file using React and JavaScript? I understand that stl files are unitless, I just need the relative dimensions of the model in the stl file.
I've looked throughout SO but haven't found any questions related to this specifically for JavaScript.
You can use STLLoader
from three.js
to get the relative dimensions of the bounding box of an stl object.
Here's a function that prints the dimensions to the console, where url
is the link to the stl file you want to use.
const calculateSTLDimensions = ({ url }) => {
const loader = new STLLoader();
loader.load(url, (geometry) => {
// Compute the bounding box
geometry.computeBoundingBox();
const boundingBox = geometry.boundingBox;
// Get the dimensions
const width = boundingBox.max.x - boundingBox.min.x;
const height = boundingBox.max.y - boundingBox.min.y;
const depth = boundingBox.max.z - boundingBox.min.z;
console.log('Width:', width);
console.log('Height:', height);
console.log('Depth:', depth);
});
return null;
};
If you want to use a stl file object instead of a url, you can use FileReader
like so
const reader = new FileReader();
reader.onload = (event) => {
const arrayBuffer = event.target.result;
const loader = new STLLoader();
const geometry = loader.parse(arrayBuffer);
// rest of the code
}