Search code examples
javascriptsvgthree.jscomputational-geometry

Extrude Geometry in three.js


I'm currently loading an STL onject into my three.js scene.

For some reason, it takes a lot of GPU resources to render/animate, slowing the entire scene down so I've been considering alternatives.

As it's quite a simple shape, I thought I could use create the 2D shape and extrude it.

The 3D shape is a square frame (it's a photo frame), no curves or any other clever geometry.

Initially, I thought about creating 4x 3D oblongs, rotating each one by 90 degrees and placing them just right in the scene to make it look like a frame - but that's not ideal.

Here's a 2D shape  (it's perfectly square):

And here's a preview of the STL model

So as an alternative to loading the STL model into the scene, how can I create this shape in three.js (with empty space in the centre) and then extrude it to give it some depth?


Solution

  • Basic extrusion example: Shape -> ExtrudeGeometry -> Mesh

    const { renderer, scene, camera } = initThree();
    
    
    //Create a frame shape..
    var frame = new THREE.Shape();
    frame.moveTo(-4, -3);
    frame.lineTo( 4, -3);
    frame.lineTo( 4,  3);
    frame.lineTo(-4,  3);
    
    //..with a hole:
    var hole = new THREE.Path();
    hole.moveTo(-3, -2);
    hole.lineTo( 3, -2);
    hole.lineTo( 3,  2);
    hole.lineTo(-3,  2);
    frame.holes.push(hole);
    
    //Extrude the shape into a geometry, and create a mesh from it:
    var extrudeSettings = {
        steps: 1,
        depth: 1,
        bevelEnabled: false,
    };
    var geom = new THREE.ExtrudeGeometry(frame, extrudeSettings);
    var mesh = new THREE.Mesh(geom, new THREE.MeshPhongMaterial({ color: 0xffaaaa }));
    
    
    scene.add(mesh);
    renderer.render(scene, camera);
    body {
        margin: 0;
        overflow: hidden;
    }
    canvas {
        display: block;
    }
    <script src="//cdnjs.cloudflare.com/ajax/libs/three.js/102/three.min.js"></script>
    <script src="//cdn.rawgit.com/Sphinxxxx/298702f070e34a5df30326cd9943260a/raw/16afc701da1ed8ed267a896907692d8acdce9b7d/init-three.js"></script>