<!DOCTYPE html><html lang="en"><head>
    <meta charset="utf-8">
    <title>Primitives</title>
    <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
    <meta name="twitter:card" content="summary_large_image">
    <meta name="twitter:site" content="@threejs">
    <meta name="twitter:title" content="Three.js – Primitives">
    <meta property="og:image" content="https://threejs.org/files/share.png">
    <link rel="shortcut icon" href="/files/favicon_white.ico" media="(prefers-color-scheme: dark)">
    <link rel="shortcut icon" href="/files/favicon.ico" media="(prefers-color-scheme: light)">

    <link rel="stylesheet" href="/manual/resources/lesson.css">
    <link rel="stylesheet" href="/manual/resources/lang.css">
  </head>
  <body>
    <div class="container">
      <div class="lesson-title">
        <h1>Primitives</h1>
      </div>
      <div class="lesson">
        <div class="lesson-main">
          <p>This article is one in a series of articles about three.js.
The first article was <a href="fundamentals.html">about fundamentals</a>.
If you haven't read that yet you might want to start there.</p>
<p>Three.js has a large number of primitives. Primitives
are generally 3D shapes that are generated at runtime
with a bunch of parameters.</p>
<p>It's common to use primitives for things like a sphere
for a globe or a bunch of boxes to draw a 3D graph. It's
especially common to use primitives to experiment
and get started with 3D. For the majority of 3D apps
it's more common to have an artist make 3D models
in a 3D modeling program like <a href="https://blender.org">Blender</a>
or <a href="https://www.autodesk.com/products/maya/">Maya</a> or <a href="https://www.maxon.net/en-us/products/cinema-4d/">Cinema 4D</a>. Later in this series we'll
cover making and loading data from several 3D modeling
programs. For now let's go over some of the available
primitives.</p>
<p>Many of the primitives below have defaults for some or all of their
parameters so you can use more or less depending on your needs.</p>
<div id="Diagram-BoxGeometry" data-primitive="BoxGeometry">A Box</div>
<div id="Diagram-CircleGeometry" data-primitive="CircleGeometry">A flat circle</div>
<div id="Diagram-ConeGeometry" data-primitive="ConeGeometry">A Cone</div>
<div id="Diagram-CylinderGeometry" data-primitive="CylinderGeometry">A Cylinder</div>
<div id="Diagram-DodecahedronGeometry" data-primitive="DodecahedronGeometry">A dodecahedron (12 sides)</div>
<div id="Diagram-ExtrudeGeometry" data-primitive="ExtrudeGeometry">An extruded 2d shape with optional bevelling.
Here we are extruding a heart shape. Note this is the basis
for <a href="/docs/#api/en/geometries/TextGeometry"><code class="notranslate" translate="no">TextGeometry</code></a>.</div>
<div id="Diagram-IcosahedronGeometry" data-primitive="IcosahedronGeometry">An icosahedron (20 sides)</div>
<div id="Diagram-LatheGeometry" data-primitive="LatheGeometry">A shape generated by spinning a line. Examples would be: lamps, bowling pins, candles, candle holders, wine glasses, drinking glasses, etc... You provide the 2d silhouette as series of points and then tell three.js how many subdivisions to make as it spins the silhouette around an axis.</div>
<div id="Diagram-OctahedronGeometry" data-primitive="OctahedronGeometry">An Octahedron (8 sides)</div>
<div id="Diagram-ParametricGeometry" data-primitive="ParametricGeometry">A surface generated by providing a function that takes a 2D point from a grid and returns the corresponding 3d point.</div>
<div id="Diagram-PlaneGeometry" data-primitive="PlaneGeometry">A 2D plane</div>
<div id="Diagram-PolyhedronGeometry" data-primitive="PolyhedronGeometry">Takes a set of triangles centered around a point and projects them onto a sphere</div>
<div id="Diagram-RingGeometry" data-primitive="RingGeometry">A 2D disc with a hole in the center</div>
<div id="Diagram-ShapeGeometry" data-primitive="ShapeGeometry">A 2D outline that gets triangulated</div>
<div id="Diagram-SphereGeometry" data-primitive="SphereGeometry">A sphere</div>
<div id="Diagram-TetrahedronGeometry" data-primitive="TetrahedronGeometry">A tetrahedron (4 sides)</div>
<div id="Diagram-TextGeometry" data-primitive="TextGeometry">3D text generated from a 3D font and a string</div>
<div id="Diagram-TorusGeometry" data-primitive="TorusGeometry">A torus (donut)</div>
<div id="Diagram-TorusKnotGeometry" data-primitive="TorusKnotGeometry">A torus knot</div>
<div id="Diagram-TubeGeometry" data-primitive="TubeGeometry">A circle traced down a path</div>
<div id="Diagram-EdgesGeometry" data-primitive="EdgesGeometry">A helper object that takes another geometry as input and generates edges only if the angle between faces is greater than some threshold. For example if you look at the box at the top it shows a line going through each face showing every triangle that makes the box. Using an <a href="/docs/#api/en/geometries/EdgesGeometry"><code class="notranslate" translate="no">EdgesGeometry</code></a> instead the middle lines are removed. Adjust the thresholdAngle below and you'll see the edges below that threshold disappear.</div>
<div id="Diagram-WireframeGeometry" data-primitive="WireframeGeometry">Generates geometry that contains one line segment (2 points) per edge in the given geometry. Without this you'd often be missing edges or get extra edges since WebGL generally requires 2 points per line segment. For example if all you had was a single triangle there would only be 3 points. If you tried to draw it using a material with <code class="notranslate" translate="no">wireframe: true</code> you would only get a single line. Passing that triangle geometry to a <a href="/docs/#api/en/geometries/WireframeGeometry"><code class="notranslate" translate="no">WireframeGeometry</code></a> will generate a new geometry that has 3 lines segments using 6 points..</div>

<p>We'll go over creating custom geometry in <a href="custom-buffergeometry.html">another article</a>. For now
let's make an example creating each type of primitive. We'll start
with the <a href="responsive.html">examples from the previous article</a>.</p>
<p>Near the top let's set a background color</p>
<pre class="prettyprint showlinemods notranslate lang-js" translate="no">const scene = new THREE.Scene();
+scene.background = new THREE.Color(0xAAAAAA);
</pre>
<p>This tells three.js to clear to lightish gray.</p>
<p>The camera needs to change position so that we can see all the
objects.</p>
<pre class="prettyprint showlinemods notranslate lang-js" translate="no">-const fov = 75;
+const fov = 40;
const aspect = 2;  // the canvas default
const near = 0.1;
-const far = 5;
+const far = 1000;
const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
-camera.position.z = 2;
+camera.position.z = 120;
</pre>
<p>Let's add a function, <code class="notranslate" translate="no">addObject</code>, that takes an x, y position and an <a href="/docs/#api/en/core/Object3D"><code class="notranslate" translate="no">Object3D</code></a> and adds
the object to the scene.</p>
<pre class="prettyprint showlinemods notranslate lang-js" translate="no">const objects = [];
const spread = 15;

function addObject(x, y, obj) {
  obj.position.x = x * spread;
  obj.position.y = y * spread;

  scene.add(obj);
  objects.push(obj);
}
</pre>
<p>Let's also make a function to create a random colored material.
We'll use a feature of <a href="/docs/#api/en/math/Color"><code class="notranslate" translate="no">Color</code></a> that lets you set a color
based on hue, saturation, and luminance.</p>
<p><code class="notranslate" translate="no">hue</code> goes from 0 to 1 around the color wheel with
red at 0, green at .33 and blue at .66. <code class="notranslate" translate="no">saturation</code>
goes from 0 to 1 with 0 having no color and 1 being
most saturated. <code class="notranslate" translate="no">luminance</code> goes from 0 to 1
with 0 being black, 1 being white and 0.5 being
the maximum amount of color. In other words
as <code class="notranslate" translate="no">luminance</code> goes from 0.0 to 0.5 the color
will go from black to <code class="notranslate" translate="no">hue</code>. From 0.5 to 1.0
the color will go from <code class="notranslate" translate="no">hue</code> to white.</p>
<pre class="prettyprint showlinemods notranslate lang-js" translate="no">function createMaterial() {
  const material = new THREE.MeshPhongMaterial({
    side: THREE.DoubleSide,
  });

  const hue = Math.random();
  const saturation = 1;
  const luminance = .5;
  material.color.setHSL(hue, saturation, luminance);

  return material;
}
</pre>
<p>We also passed <code class="notranslate" translate="no">side: THREE.DoubleSide</code> to the material.
This tells three to draw both sides of the triangles
that make up a shape. For a solid shape like a sphere
or a cube there's usually no reason to draw the
back sides of triangles as they all face inside the
shape. In our case though we are drawing a few things
like the <a href="/docs/#api/en/geometries/PlaneGeometry"><code class="notranslate" translate="no">PlaneGeometry</code></a> and the <a href="/docs/#api/en/geometries/ShapeGeometry"><code class="notranslate" translate="no">ShapeGeometry</code></a>
which are 2 dimensional and so have no inside. Without
setting <code class="notranslate" translate="no">side: THREE.DoubleSide</code> they would disappear
when looking at their back sides.</p>
<p>I should note that it's faster to draw when <strong>not</strong> setting
<code class="notranslate" translate="no">side: THREE.DoubleSide</code> so ideally we'd set it only on
the materials that really need it but in this case we
are not drawing too much so there isn't much reason to
worry about it.</p>
<p>Let's make a function, <code class="notranslate" translate="no">addSolidGeometry</code>, that
we pass a geometry and it creates a random colored
material via <code class="notranslate" translate="no">createMaterial</code> and adds it to the scene
via <code class="notranslate" translate="no">addObject</code>.</p>
<pre class="prettyprint showlinemods notranslate lang-js" translate="no">function addSolidGeometry(x, y, geometry) {
  const mesh = new THREE.Mesh(geometry, createMaterial());
  addObject(x, y, mesh);
}
</pre>
<p>Now we can use this for the majority of the primitives we create.
For example creating a box</p>
<pre class="prettyprint showlinemods notranslate lang-js" translate="no">{
  const width = 8;
  const height = 8;
  const depth = 8;
  addSolidGeometry(-2, -2, new THREE.BoxGeometry(width, height, depth));
}
</pre>
<p>If you look in the code below you'll see a similar section for each type of geometry.</p>
<p>Here's the result:</p>
<p></p><div translate="no" class="threejs_example_container notranslate">
  <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/primitives.html"></iframe></div>
  <a class="threejs_center" href="/manual/examples/primitives.html" target="_blank">click here to open in a separate window</a>
</div>

<p></p>
<p>There are a couple of notable exceptions to the pattern above.
The biggest is probably the <a href="/docs/#api/en/geometries/TextGeometry"><code class="notranslate" translate="no">TextGeometry</code></a>. It needs to load
3D font data before it can generate a mesh for the text.
That data loads asynchronously so we need to wait for it
to load before trying to create the geometry. By promisifiying 
font loading we can make it mush easier.
We create a <a href="/docs/#api/en/loaders/FontLoader"><code class="notranslate" translate="no">FontLoader</code></a> and then a function <code class="notranslate" translate="no">loadFont</code> that returns
a promise that on resolve will give us the font. We then create
an <code class="notranslate" translate="no">async</code> function called <code class="notranslate" translate="no">doit</code> and load the font using <code class="notranslate" translate="no">await</code>.
And finally create the geometry and call <code class="notranslate" translate="no">addObject</code> to add it the scene.</p>
<pre class="prettyprint showlinemods notranslate lang-js" translate="no">{
  const loader = new FontLoader();
  // promisify font loading
  function loadFont(url) {
    return new Promise((resolve, reject) =&gt; {
      loader.load(url, resolve, undefined, reject);
    });
  }

  async function doit() {
    const font = await loadFont('resources/threejs/fonts/helvetiker_regular.typeface.json');  /* threejs.org: url */
    const geometry = new TextGeometry('three.js', {
      font: font,
      size: 3.0,
      height: .2,
      curveSegments: 12,
      bevelEnabled: true,
      bevelThickness: 0.15,
      bevelSize: .3,
      bevelSegments: 5,
    });
    const mesh = new THREE.Mesh(geometry, createMaterial());
    geometry.computeBoundingBox();
    geometry.boundingBox.getCenter(mesh.position).multiplyScalar(-1);

    const parent = new THREE.Object3D();
    parent.add(mesh);

    addObject(-1, -1, parent);
  }
  doit();
}
</pre>
<p>There's one other difference. We want to spin the text around its
center but by default three.js creates the text such that its center of rotation
is on the left edge. To work around this we can ask three.js to compute the bounding
box of the geometry. We can then call the <code class="notranslate" translate="no">getCenter</code> method
of the bounding box and pass it our mesh's position object.
<code class="notranslate" translate="no">getCenter</code> copies the center of the box into the position.
It also returns the position object so we can call <code class="notranslate" translate="no">multiplyScalar(-1)</code>
to position the entire object such that its center of rotation
is at the center of the object.</p>
<p>If we then just called <code class="notranslate" translate="no">addSolidGeometry</code> like with previous
examples it would set the position again which is
no good. So, in this case we create an <a href="/docs/#api/en/core/Object3D"><code class="notranslate" translate="no">Object3D</code></a> which
is the standard node for the three.js scene graph. <a href="/docs/#api/en/objects/Mesh"><code class="notranslate" translate="no">Mesh</code></a>
is inherited from <a href="/docs/#api/en/core/Object3D"><code class="notranslate" translate="no">Object3D</code></a> as well. We'll cover <a href="scenegraph.html">how the scene graph
works in another article</a>.
For now it's enough to know that
like DOM nodes, children are drawn relative to their parent.
By making an <a href="/docs/#api/en/core/Object3D"><code class="notranslate" translate="no">Object3D</code></a> and making our mesh a child of that
we can position the <a href="/docs/#api/en/core/Object3D"><code class="notranslate" translate="no">Object3D</code></a> wherever we want and still
keep the center offset we set earlier.</p>
<p>If we didn't do this the text would spin off center.</p>
<p></p><div translate="no" class="threejs_example_container notranslate">
  <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/primitives-text.html"></iframe></div>
  <a class="threejs_center" href="/manual/examples/primitives-text.html" target="_blank">click here to open in a separate window</a>
</div>

<p></p>
<p>Notice the one on the left is not spinning around its center
whereas the one on the right is.</p>
<p>The other exceptions are the 2 line based examples for <a href="/docs/#api/en/geometries/EdgesGeometry"><code class="notranslate" translate="no">EdgesGeometry</code></a>
and <a href="/docs/#api/en/geometries/WireframeGeometry"><code class="notranslate" translate="no">WireframeGeometry</code></a>. Instead of calling <code class="notranslate" translate="no">addSolidGeometry</code> they call
<code class="notranslate" translate="no">addLineGeometry</code> which looks like this</p>
<pre class="prettyprint showlinemods notranslate lang-js" translate="no">function addLineGeometry(x, y, geometry) {
  const material = new THREE.LineBasicMaterial({color: 0x000000});
  const mesh = new THREE.LineSegments(geometry, material);
  addObject(x, y, mesh);
}
</pre>
<p>It creates a black <a href="/docs/#api/en/materials/LineBasicMaterial"><code class="notranslate" translate="no">LineBasicMaterial</code></a> and then creates a <a href="/docs/#api/en/objects/LineSegments"><code class="notranslate" translate="no">LineSegments</code></a>
object which is a wrapper for <a href="/docs/#api/en/objects/Mesh"><code class="notranslate" translate="no">Mesh</code></a> that helps three know you're rendering
line segments (2 points per segment).</p>
<p>Each of the primitives has several parameters you can pass on creation
and it's best to <a href="https://threejs.org/docs/">look in the documentation</a> for all of them rather than
repeat them here. You can also click the links above next to each shape
to take you directly to the docs for that shape.</p>
<p>There is one other pair of classes that doesn't really fit the patterns above. Those are
the <a href="/docs/#api/en/materials/PointsMaterial"><code class="notranslate" translate="no">PointsMaterial</code></a> and the <a href="/docs/#api/en/objects/Points"><code class="notranslate" translate="no">Points</code></a> class. <a href="/docs/#api/en/objects/Points"><code class="notranslate" translate="no">Points</code></a> is like <a href="/docs/#api/en/objects/LineSegments"><code class="notranslate" translate="no">LineSegments</code></a> above in that it takes a
a <a href="/docs/#api/en/core/BufferGeometry"><code class="notranslate" translate="no">BufferGeometry</code></a> but draws points at each vertex instead of lines.
To use it you also need to pass it a <a href="/docs/#api/en/materials/PointsMaterial"><code class="notranslate" translate="no">PointsMaterial</code></a> which
take a <a href="/docs/#api/en/materials/PointsMaterial#size"><code class="notranslate" translate="no">size</code></a> for how large to make the points.</p>
<pre class="prettyprint showlinemods notranslate lang-js" translate="no">const radius = 7;
const widthSegments = 12;
const heightSegments = 8;
const geometry = new THREE.SphereGeometry(radius, widthSegments, heightSegments);
const material = new THREE.PointsMaterial({
    color: 'red',
    size: 0.2,     // in world units
});
const points = new THREE.Points(geometry, material);
scene.add(points);
</pre>
<div class="spread">
<div data-diagram="Points"></div>
</div>

<p>You can turn off <a href="/docs/#api/en/materials/PointsMaterial#sizeAttenuation"><code class="notranslate" translate="no">sizeAttenuation</code></a> by setting it to false if you want the points to
be the same size regardless of their distance from the camera.</p>
<pre class="prettyprint showlinemods notranslate lang-js" translate="no">const material = new THREE.PointsMaterial({
    color: 'red',
+    sizeAttenuation: false,
+    size: 3,       // in pixels
-    size: 0.2,     // in world units
});
...
</pre>
<div class="spread">
<div data-diagram="PointsUniformSize"></div>
</div>

<p>One other thing that's important to cover is that almost all shapes
have various settings for how much to subdivide them. A good example
might be the sphere geometries. Spheres take parameters for
how many divisions to make around and how many top to bottom. For example</p>
<div class="spread">
<div data-diagram="SphereGeometryLow"></div>
<div data-diagram="SphereGeometryMedium"></div>
<div data-diagram="SphereGeometryHigh"></div>
</div>

<p>The first sphere has 5 segments around and 3 high which is 15 segments
or 30 triangles. The second sphere has 24 segments by 10. That's 240 segments
or 480 triangles. The last one has 50 by 50 which is 2500 segments or 5000 triangles.</p>
<p>It's up to you to decide how many subdivisions you need. It might
look like you need a high number of segments but remove the lines
and the flat shading and we get this</p>
<div class="spread">
<div data-diagram="SphereGeometryLowSmooth"></div>
<div data-diagram="SphereGeometryMediumSmooth"></div>
<div data-diagram="SphereGeometryHighSmooth"></div>
</div>

<p>It's now not so clear that the one on the right with 5000 triangles
is entirely better than the one in the middle with only 480.
If you're only drawing a few spheres, like say a single globe for
a map of the earth, then a single 10000 triangle sphere is not a bad
choice. If on the other hand you're trying to draw 1000 spheres
then 1000 spheres times 10000 triangles each is 10 million triangles.
To animate smoothly you need the browser to draw at 60 frames per
second so you'd be asking the browser to draw 600 million triangles
per second. That's a lot of computing.</p>
<p>Sometimes it's easy to choose. For example you can also choose
to subdivide a plane.</p>
<div class="spread">
<div data-diagram="PlaneGeometryLow"></div>
<div data-diagram="PlaneGeometryHigh"></div>
</div>

<p>The plane on the left is 2 triangles. The plane on the right
is 200 triangles. Unlike the sphere there is really no trade off in quality for most
use cases of a plane. You'd most likely only subdivide a plane
if you expected to want to modify or warp it in some way. A box
is similar.</p>
<p>So, choose whatever is appropriate for your situation. The less
subdivisions you choose the more likely things will run smoothly and the less
memory they'll take. You'll have to decide for yourself what the correct
tradeoff is for your particular situation.</p>
<p>If none of the shapes above fit your use case you can load
geometry for example from a <a href="load-obj.html">.obj file</a>
or a <a href="load-gltf.html">.gltf file</a>. 
You can also create your own <a href="custom-buffergeometry.html">custom BufferGeometry</a>.</p>
<p>Next up let's go over <a href="scenegraph.html">how three's scene graph works and how
to use it</a>.</p>
<p><link rel="stylesheet" href="../resources/threejs-primitives.css"></p>
<script type="module" src="../resources/threejs-primitives.js"></script>


        </div>
      </div>
    </div>
  
  <script src="/manual/resources/prettify.js"></script>
  <script src="/manual/resources/lesson.js"></script>




</body></html>