Learning Three.js

or WebGL for Dummies

Constructive Solid Geometry With csg.js

This post is about constructive solid geometry , an impressive word :) In fact, it is just a way to build complex objects from simpler ones. Those simple objects are assembled using operations such as union, difference and intersection.

Recently Evan Wallas released csg.js, a clean self-contained library to do constructive solid geometry. So Chandler Prall wrote a bridge to make it easy to use with three.js.

With all this nice code, i wrote the little demo of a dice you can see on the right. Thus you can click to change the operations, play with it and have a feel of the various operations.

Let’s start

So lets see how to use it. First step, you download csg.js from here , ThreeCSG.js bridge from here . Then include those line in your own code.

<script src="csg.js"></script>
<script src="ThreeCSG.js"></script>

Let’s convert

Ok now that we got the source, let’s use it. ThreeCSG.js is a bridge between three.js and csg.js. Both libraries use a different format for geometry. ThreeCSG.js does the conversion back and forth. To convert your three.js geometry to a csg geometry, use this line.

var geometryCsg    = THREE.CSG.toCSG(geometryThree);

Then you likely apply boolean operations on csg.js geometry. To convert it back to three.js, just do

var geometryThree  = THREE.CSG.fromCSG(geometryCsg);

You end up with a normal three.js geometry than you can use everywhere, like GeometryUtils or Mesh.

Let’s assemble

Now the fun part, lets assemble objects with those misterious boolean operations on ours csg.js geometries. There are 3 of them: difference, union and intersect. To build our dice, first we build a cube then we subtract a bunch of spheres to makes the holes.

Once you converted your objects, you apply operations on them. For the dice, we use .subtract().


But it is possible to use .union() to add them.


Or to keep only the common part of both objects with .intersect().

You can chain those operations to your own taste. Up to you to be creative :)



Constructive solid Geometry is simple and quite powerfull. csg.js , ThreeCSG.js and three.js makes it real easy to play with. You may look at the source of our dice demo to see a working version of this code. That’s all for today, have fun :)