<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Mirian Ezeamama on Medium]]></title>
        <description><![CDATA[Stories by Mirian Ezeamama on Medium]]></description>
        <link>https://medium.com/@chiomsyndev?source=rss-39943d331ca7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*TlN83SsaHNIgtUDoKfTtEA.jpeg</url>
            <title>Stories by Mirian Ezeamama on Medium</title>
            <link>https://medium.com/@chiomsyndev?source=rss-39943d331ca7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 17:42:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chiomsyndev/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Learning Three.js with React Three Fiber — Day 19: Measuring Angles Between Three Points in 3D]]></title>
            <link>https://medium.com/@chiomsyndev/learning-three-js-with-react-three-fiber-day-19-measuring-angles-between-three-points-in-3d-904cf2f1e1a8?source=rss-39943d331ca7------2</link>
            <guid isPermaLink="false">https://medium.com/p/904cf2f1e1a8</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[3d-design]]></category>
            <category><![CDATA[threejs]]></category>
            <dc:creator><![CDATA[Mirian Ezeamama]]></dc:creator>
            <pubDate>Thu, 19 Nov 2026 13:01:45 GMT</pubDate>
            <atom:updated>2026-11-19T13:01:45.566Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UXHOeKNs5e-2eVEBPI5umg.png" /></figure><h3>Introduction</h3><p>Welcome back to my journey of learning Three.js with React Three Fiber!</p><p>In Day 18, I learned how to measure the distance between two points in a 3D scene.</p><p>I discovered that Three.js provides a method called distanceTo() that calculates the straight-line distance between two positions.</p><p>For example:</p><pre>const pointA = new Vector3(1, 0, 0);<br>const pointB = new Vector3(4, 0, 0);</pre><pre>const distance = pointA.distanceTo(pointB);</pre><pre>console.log(distance); // 3</pre><p>That was exciting because it showed me how mathematics could become a practical feature inside a 3D application.</p><p>But it also made me curious.</p><p><strong>What if I wanted to measure an angle instead of a distance?</strong></p><p>Imagine selecting three points on a 3D model and asking the application to calculate the angle between them.</p><p>That is exactly what I’m learning today.</p><p>In this tutorial, I’ll explore how angles work in 3D space, how Three.js calculates them using vectors, and how to build a simple interactive angle measurement tool using React Three Fiber.</p><p>Let’s begin!</p><h3>1. What Is an Angle?</h3><p>Before writing any code, I needed to understand what an angle actually represents.</p><p>An angle describes how much one direction turns away from another direction.</p><p>Imagine standing in a room and pointing your right arm straight ahead.</p><p>Now imagine rotating your arm towards your right.</p><p>The amount of rotation between the original direction and the new direction is an angle.</p><p>We commonly measure angles in degrees.</p><p>For example:</p><ul><li><strong>0°:</strong> Two directions point the same way.</li><li><strong>45°:</strong> The directions form a relatively narrow angle.</li><li><strong>90°:</strong> The directions are perpendicular.</li><li><strong>180°:</strong> The directions point in opposite directions.</li></ul><p>An important discovery for me was that angles are not limited to flat drawings.</p><p>We can also measure angles between directions in 3D space.</p><p>This is useful when working with 3D models, geometry, computer graphics, engineering, and measurement applications.</p><h3>2. Why Do We Need Three Points?</h3><p>In Day 18, I needed two points to measure a distance.</p><p>But to measure an angle formed by connected line segments, I need three points.</p><p>Let’s call them:</p><ul><li>Point A</li><li>Point B</li><li>Point C</li></ul><p>Imagine the following simple diagram:</p><pre>A<br> \<br>  \<br>   B -------- C</pre><p>Point B is where the two lines meet.</p><p>This meeting point is called the <strong>vertex</strong>.</p><p>The angle we want to measure is the angle at B.</p><p>Mathematically, we write it as:</p><p><strong>∠ABC</strong></p><p>Notice that B appears in the middle.</p><p>That is important because the middle letter identifies the vertex.</p><p>If I change the vertex, I might calculate a completely different angle.</p><h3>A real-world example</h3><p>Imagine a person’s elbow.</p><p>I could identify three anatomical landmarks representing the upper arm, elbow, and forearm.</p><p>Those landmarks could help define two directions meeting at the elbow.</p><p>With the appropriate clinical measurement convention, the angle between those directions could be used in a joint assessment.</p><p>For now, however, I’ll focus on understanding the mathematics rather than clinical measurements.</p><h3>3. Understanding Vectors Again</h3><p>This is where today’s lesson connects to something I learned earlier.</p><p>In Three.js, a vector can represent a position, direction, or displacement.</p><p>For example:</p><pre>const position = new Vector3(3, 2, 5);</pre><p>This creates a vector with three components:</p><pre>X = 3<br>Y = 2<br>Z = 5</pre><p>But here’s something I initially found confusing.</p><p><strong>How can I use a position to calculate a direction?</strong></p><p>The answer is subtraction.</p><p>Suppose I have two points:</p><pre>const pointA = new Vector3(5, 0, 0);<br>const pointB = new Vector3(2, 0, 0);</pre><p>If I subtract B from A:</p><pre>const direction = pointA.clone().sub(pointB);</pre><p>I get:</p><pre>(5, 0, 0) - (2, 0, 0)</pre><pre>= (3, 0, 0)</pre><p>The result describes a displacement of three units in the positive X direction.</p><p>This means that by subtracting two positions, I can create a vector pointing from one position to another.</p><p>That is exactly what we need for angle measurement.</p><h3>4. Creating Two Direction Vectors</h3><p>Remember our three points:</p><p>A, B, and C.</p><p>We want to measure the angle at B.</p><p>Therefore, we need two vectors that both start at B:</p><p><strong>Vector BA:</strong> Points from B towards A.</p><p><strong>Vector BC:</strong> Points from B towards C.</p><p>Mathematically:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/208/1*Z_si6sjyxhSCIKPcfBQCew.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/201/1*xmdUD8vW6riBZhNvKEYl2A.png" /></figure><p>Let’s write that in Three.js.</p><pre>import { Vector3 } from &quot;three&quot;;</pre><pre>const pointA = new Vector3(-2, 0, 0);<br>const pointB = new Vector3(0, 0, 0);<br>const pointC = new Vector3(0, 0, 2);</pre><pre>const directionBA = pointA.clone().sub(pointB);<br>const directionBC = pointC.clone().sub(pointB);</pre><h3>Understanding the code</h3><p>First:</p><pre>const pointA = new Vector3(-2, 0, 0);</pre><p>This creates Point A at X = -2, Y = 0, and Z = 0.</p><p>Next:</p><pre>const pointB = new Vector3(0, 0, 0);</pre><p>This creates Point B at the origin.</p><p>The origin is the position where X, Y, and Z are all zero.</p><p>Then:</p><pre>const pointC = new Vector3(0, 0, 2);</pre><p>This creates Point C two units along the positive Z axis.</p><p>Now comes the important part:</p><pre>const directionBA = pointA.clone().sub(pointB);</pre><p>I use .clone() to create a copy of Point A.</p><p>Why?</p><p>Because .sub() modifies the vector on which it is called.</p><p>If I wrote:</p><pre>pointA.sub(pointB);</pre><p>Three.js would modify the original pointA object.</p><p>Using .clone() helps me preserve the original point coordinates.</p><p>The resulting vectors are:</p><pre>BA = (-2, 0, 0)</pre><pre>BC = (0, 0, 2)</pre><p>These vectors point in perpendicular directions.</p><p>Therefore, the angle between them should be 90°.</p><p>But how do I calculate that using code?</p><h3>5. Meet Vector3.angleTo()</h3><p>Three.js has a method called:</p><pre>angleTo()</pre><p>It calculates the angle between two vectors.</p><p>Let’s try it:</p><pre>const angle = directionBA.angleTo(directionBC);</pre><pre>console.log(angle);</pre><p>The result is approximately:</p><pre>1.5707963267948966</pre><p>When I first saw a number like this, I might have expected 90.</p><p>So why did Three.js return approximately 1.57?</p><p>Because <strong>Three.js returns the angle in radians, not degrees.</strong></p><p>This brings us to another important concept.</p><h3>6. What Are Radians?</h3><p>Before learning 3D programming, I was more familiar with degrees.</p><p>I knew that:</p><ul><li>A quarter turn is 90°.</li><li>A half turn is 180°.</li><li>A complete turn is 360°.</li></ul><p>But in mathematics and computer graphics, angles are also measured in radians.</p><p>Radians are another unit for measuring angles.</p><p>Think of degrees and radians like centimetres and inches.</p><p>They describe the same kind of measurement but use different units.</p><p>Here are some common conversions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*dr4PdxI_gEQfQGAimXLgTw.png" /></figure><p>So when Three.js returns approximately 1.571 radians, that corresponds to 90°.</p><h3>Converting radians into degrees</h3><p>The mathematical formula is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*vwc4VJgrA6XfnFe9o0jCIQ.png" /></figure><p>We could write:</p><pre>const degrees = angle * (180 / Math.PI);</pre><p>But Three.js already provides a convenient helper:</p><pre>import { MathUtils } from &quot;three&quot;;</pre><pre>const degrees = MathUtils.radToDeg(angle);</pre><p>Now:</p><pre>console.log(degrees); // 90</pre><p>Much easier to understand!</p><h3>7. Building a Reusable Angle Calculation Function</h3><p>Now that I understand the basic mathematics, I want to create a reusable function.</p><p>Instead of rewriting the calculation every time, I’ll create a function that accepts three points and returns the angle in degrees.</p><pre>import { MathUtils, Vector3 } from &quot;three&quot;;</pre><pre>type Point = [number, number, number];</pre><pre>function calculateAngle(<br>  pointA: Point,<br>  pointB: Point,<br>  pointC: Point<br>): number | null {<br>  const A = new Vector3(...pointA);<br>  const B = new Vector3(...pointB);<br>  const C = new Vector3(...pointC);</pre><pre>  const directionBA = A.sub(B);<br>  const directionBC = C.sub(B);</pre><pre>  if (<br>    directionBA.lengthSq() &lt; 1e-8 ||<br>    directionBC.lengthSq() &lt; 1e-8<br>  ) {<br>    return null;<br>  }</pre><pre>  const angleInRadians = directionBA.angleTo(directionBC);</pre><pre>  return MathUtils.radToDeg(angleInRadians);<br>}</pre><p>Let’s understand it.</p><h3>What is type Point?</h3><pre>type Point = [number, number, number];</pre><p>This is a TypeScript tuple.</p><p>It tells TypeScript that each point must contain exactly three numbers.</p><p>For example:</p><pre>const point: Point = [1, 2, 3];</pre><p>The values represent X, Y, and Z.</p><h3>What does ...pointA mean?</h3><pre>const A = new Vector3(...pointA);</pre><p>The three dots are JavaScript’s spread syntax.</p><p>They take the values from the array and pass them as separate arguments.</p><p>So:</p><pre>new Vector3(...[1, 2, 3]);</pre><p>is equivalent to:</p><pre>new Vector3(1, 2, 3);</pre><h3>Why do we subtract B?</h3><pre>const directionBA = A.sub(B);<br>const directionBC = C.sub(B);</pre><p>Because B is the vertex.</p><p>We need both vectors to point away from B.</p><p>Notice that A, B, and C were created as new Vector3 objects inside the function. Modifying A and C with .sub() is safe here because we are not modifying the original input arrays.</p><h3>Why do we check lengthSq()?</h3><pre>if (<br>  directionBA.lengthSq() &lt; 1e-8 ||<br>  directionBC.lengthSq() &lt; 1e-8<br>) {<br>  return null;<br>}</pre><p>Imagine selecting A and B at the same position.</p><p>The vector BA would have zero length.</p><p>A zero-length vector has no meaningful direction, so we cannot use it to define an angle.</p><p>lengthSq() calculates the squared length of a vector.</p><p>We compare it against a very small number to reject zero or extremely short vectors.</p><p>The 1e-8 value is a small tolerance for this example. In a real measurement application, the tolerance should be chosen based on the model&#39;s coordinate units and required precision.</p><h3>Why return null?</h3><p>If the angle cannot be calculated, returning null lets the rest of the application know that no valid measurement is available.</p><p>Otherwise, the function returns a number representing the angle in degrees.</p><h3>8. Creating an Interactive Angle Measurement Tool</h3><p>Now comes my favourite part: turning the mathematics into something visual.</p><p>I want to build a React Three Fiber scene where I can:</p><ol><li>Click once to select Point A.</li><li>Click again to select Point B.</li><li>Click a third time to select Point C.</li><li>Draw two lines connecting A to B and B to C.</li><li>Calculate the angle at B.</li><li>Display the result in the scene.</li><li>Reset the measurement and start again.</li></ol><p>For this beginner example, I’ll select points on a flat horizontal surface.</p><p>The calculation itself works with points anywhere in 3D space.</p><h3>Complete React Three Fiber code</h3><pre>&quot;use client&quot;;</pre><pre>import { useState } from &quot;react&quot;;<br>import { Canvas, type ThreeEvent } from &quot;@react-three/fiber&quot;;<br>import { Html, Line, OrbitControls } from &quot;@react-three/drei&quot;;<br>import { MathUtils, Vector3 } from &quot;three&quot;;</pre><pre>type Point = [number, number, number];</pre><pre>function calculateAngle(<br>  pointA: Point,<br>  pointB: Point,<br>  pointC: Point<br>): number | null {<br>  const A = new Vector3(...pointA);<br>  const B = new Vector3(...pointB);<br>  const C = new Vector3(...pointC);</pre><pre>  const directionBA = A.sub(B);<br>  const directionBC = C.sub(B);</pre><pre>  if (<br>    directionBA.lengthSq() &lt; 1e-8 ||<br>    directionBC.lengthSq() &lt; 1e-8<br>  ) {<br>    return null;<br>  }</pre><pre>  const radians = directionBA.angleTo(directionBC);</pre><pre>  return MathUtils.radToDeg(radians);<br>}</pre><pre>function AngleScene() {<br>  const [points, setPoints] = useState&lt;Point[]&gt;([]);</pre><pre>  function handleFloorClick(event: ThreeEvent&lt;MouseEvent&gt;) {<br>    if (points.length &gt;= 3) return;</pre><pre>    const { x, z } = event.point;</pre><pre>    const newPoint: Point = [x, 0.08, z];</pre><pre>    setPoints((previous) =&gt; [...previous, newPoint]);<br>  }</pre><pre>  const angle =<br>    points.length === 3<br>      ? calculateAngle(points[0], points[1], points[2])<br>      : null;</pre><pre>  return (<br>    &lt;&gt;<br>      &lt;ambientLight intensity={0.7} /&gt;</pre><pre>      &lt;directionalLight<br>        position={[5, 8, 5]}<br>        intensity={1.2}<br>      /&gt;</pre><pre>      &lt;mesh<br>        rotation={[-Math.PI / 2, 0, 0]}<br>        onClick={handleFloorClick}<br>      &gt;<br>        &lt;planeGeometry args={[20, 20]} /&gt;<br>        &lt;meshStandardMaterial color=&quot;#e8eef5&quot; /&gt;<br>      &lt;/mesh&gt;</pre><pre>      &lt;gridHelper<br>        args={[20, 20, &quot;#94a3b8&quot;, &quot;#cbd5e1&quot;]}<br>        position={[0, 0.01, 0]}<br>      /&gt;</pre><pre>      {points.map((point, index) =&gt; (<br>        &lt;group key={index} position={point}&gt;<br>          &lt;mesh&gt;<br>            &lt;sphereGeometry args={[0.12, 24, 24]} /&gt;<br>            &lt;meshStandardMaterial<br>              color={[&quot;#2563eb&quot;, &quot;#f59e0b&quot;, &quot;#16a34a&quot;][index]}<br>            /&gt;<br>          &lt;/mesh&gt;</pre><pre>          &lt;Html<br>            position={[0, 0.3, 0]}<br>            center<br>            style={{<br>              pointerEvents: &quot;none&quot;,<br>              fontWeight: &quot;bold&quot;,<br>              color: &quot;#111827&quot;,<br>            }}<br>          &gt;<br>            {[&quot;A&quot;, &quot;B&quot;, &quot;C&quot;][index]}<br>          &lt;/Html&gt;<br>        &lt;/group&gt;<br>      ))}</pre><pre>      {points.length &gt;= 2 &amp;&amp; (<br>        &lt;Line<br>          points={[points[0], points[1]]}<br>          color=&quot;#2563eb&quot;<br>          lineWidth={3}<br>        /&gt;<br>      )}</pre><pre>      {points.length === 3 &amp;&amp; (<br>        &lt;&gt;<br>          &lt;Line<br>            points={[points[1], points[2]]}<br>            color=&quot;#16a34a&quot;<br>            lineWidth={3}<br>          /&gt;</pre><pre>          {angle !== null &amp;&amp; (<br>            &lt;Html<br>              position={[<br>                points[1][0],<br>                points[1][1] + 0.7,<br>                points[1][2],<br>              ]}<br>              center<br>              style={{<br>                background: &quot;white&quot;,<br>                color: &quot;#111827&quot;,<br>                padding: &quot;8px 12px&quot;,<br>                borderRadius: &quot;8px&quot;,<br>                fontWeight: &quot;bold&quot;,<br>                whiteSpace: &quot;nowrap&quot;,<br>                pointerEvents: &quot;none&quot;,<br>              }}<br>            &gt;<br>              {angle.toFixed(1)}°<br>            &lt;/Html&gt;<br>          )}<br>        &lt;/&gt;<br>      )}</pre><pre>      &lt;OrbitControls makeDefault /&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><pre>export default function AngleMeasurement() {<br>  const [resetKey, setResetKey] = useState(0);</pre><pre>  return (<br>    &lt;div&gt;<br>      &lt;div style={{ height: 500, width: &quot;100%&quot; }}&gt;<br>        &lt;Canvas<br>          key={resetKey}<br>          camera={{<br>            position: [5, 7, 8],<br>            fov: 50,<br>          }}<br>        &gt;<br>          &lt;AngleScene /&gt;<br>        &lt;/Canvas&gt;<br>      &lt;/div&gt;</pre><pre>      &lt;button<br>        type=&quot;button&quot;<br>        onClick={() =&gt; setResetKey((value) =&gt; value + 1)}<br>      &gt;<br>        Reset measurement<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><h3>9. Understanding How the Interactive Tool Works</h3><p>Let’s examine the most important parts.</p><h3>Step 1: Storing the selected points</h3><pre>const [points, setPoints] = useState&lt;Point[]&gt;([]);</pre><p>React’s useState() allows us to store information that can change.</p><p>Initially, we have no selected points:</p><pre>[]</pre><p>After the first click, we have:</p><pre>[A]</pre><p>After the second click:</p><pre>[A, B]</pre><p>After the third click:</p><pre>[A, B, C]</pre><p>Each time the state changes, React updates the scene.</p><h3>Step 2: Detecting where the user clicks</h3><pre>function handleFloorClick(event: ThreeEvent&lt;MouseEvent&gt;) {<br>  if (points.length &gt;= 3) return;</pre><pre>  const { x, z } = event.point;</pre><pre>  const newPoint: Point = [x, 0.08, z];</pre><pre>  setPoints((previous) =&gt; [...previous, newPoint]);<br>}</pre><p>When I click the floor, React Three Fiber provides an event containing information about the intersection.</p><p>The event.point property contains the 3D position where the click hit the floor.</p><p>Since the floor is horizontal, I use the X and Z coordinates.</p><p>I set Y to 0.08 to place the measurement markers slightly above the surface.</p><p>The state update adds the new point to the existing array.</p><h3>Step 3: Drawing the measurement points</h3><pre>{points.map((point, index) =&gt; (<br>  &lt;group key={index} position={point}&gt;<br>    &lt;mesh&gt;<br>      &lt;sphereGeometry args={[0.12, 24, 24]} /&gt;<br>      &lt;meshStandardMaterial color=&quot;#2563eb&quot; /&gt;<br>    &lt;/mesh&gt;<br>  &lt;/group&gt;<br>))}</pre><p>The map() method loops through our selected points.</p><p>For each point, we create a small sphere.</p><p>The sphere helps us see exactly where the user clicked.</p><p>In the complete example, each point also gets its own colour and letter label.</p><h3>Step 4: Drawing the lines</h3><p>We use the Line component from Drei.</p><pre>&lt;Line<br>  points={[points[0], points[1]]}<br>  color=&quot;#2563eb&quot;<br>  lineWidth={3}<br>/&gt;</pre><p>This draws a line between A and B.</p><p>Then:</p><pre>&lt;Line<br>  points={[points[1], points[2]]}<br>  color=&quot;#16a34a&quot;<br>  lineWidth={3}<br>/&gt;</pre><p>This draws another line between B and C.</p><p>The two lines meet at B, creating the angle we want to measure.</p><h3>Step 5: Displaying the angle</h3><p>We use the Html component from Drei.</p><pre>&lt;Html<br>  position={[<br>    points[1][0],<br>    points[1][1] + 0.7,<br>    points[1][2],<br>  ]}<br>  center<br>&gt;<br>  {angle.toFixed(1)}°<br>&lt;/Html&gt;</pre><p>This displays the calculated angle slightly above B.</p><p>The toFixed(1) method rounds the displayed value to one decimal place.</p><p>For example:</p><pre>90.0°<br>45.2°<br>135.8°</pre><p>The underlying calculation is not limited to one decimal place. We are only formatting the displayed result.</p><h3>Step 6: Resetting the tool</h3><pre>const [resetKey, setResetKey] = useState(0);</pre><p>And:</p><pre>&lt;Canvas key={resetKey}&gt;<br>  &lt;AngleScene /&gt;<br>&lt;/Canvas&gt;</pre><p>When the reset button changes resetKey, React remounts the Canvas and its child scene.</p><p>Because AngleScene is created again, its points state returns to an empty array.</p><p>This is a simple solution for our learning example. In a larger application, we could keep the points state in a parent component and clear it directly without remounting the entire Canvas.</p><h3>10. Something Important I Learned: Camera Rotation Doesn’t Change the Angle</h3><p>This is one of the most interesting things about 3D measurement.</p><p>Suppose I calculate an angle of 90° between three points.</p><p>Then I rotate the camera using OrbitControls.</p><p>The lines may look different from the new camera position.</p><p>One might appear shorter, or the angle might look narrower on the screen.</p><p>But the actual calculated angle remains 90°.</p><p>Why?</p><p>Because the calculation uses the original 3D coordinates.</p><p>It does not calculate the angle from the pixels displayed on my monitor.</p><p>This is an important difference between measuring something in 3D space and estimating an angle from a 2D image.</p><h3>11. A Small Experiment: Testing Different Angles</h3><p>Let’s test the calculation without clicking anything.</p><h3>Example 1: A right angle</h3><pre>const angle = calculateAngle(<br>  [1, 0, 0],<br>  [0, 0, 0],<br>  [0, 0, 1]<br>);</pre><pre>console.log(angle); // 90</pre><h3>Example 2: A straight angle</h3><pre>const angle = calculateAngle(<br>  [-1, 0, 0],<br>  [0, 0, 0],<br>  [1, 0, 0]<br>);</pre><pre>console.log(angle); // 180</pre><h3>Example 3: A 45-degree angle</h3><pre>const angle = calculateAngle(<br>  [1, 0, 0],<br>  [0, 0, 0],<br>  [1, 0, 1]<br>);</pre><pre>console.log(angle); // Approximately 45</pre><p>Notice that we don’t need to know the lengths of the two line segments in advance.</p><p>We only need their directions.</p><p>This is because the angle between two nonzero vectors depends on their directions, not their lengths.</p><h3>12. Do We Need to Normalize the Vectors First?</h3><p>This is a question I found especially useful because I previously learned about .normalize().</p><p>Normalization changes a vector’s length to 1 while preserving its direction.</p><p>For example:</p><pre>const direction = new Vector3(3, 4, 0);</pre><pre>direction.normalize();</pre><p>The original vector has length 5.</p><p>After normalization, it becomes:</p><pre>(0.6, 0.8, 0)</pre><p>Its length is now 1.</p><p>But do we need to normalize both vectors before calling angleTo()?</p><p><strong>No.</strong></p><p>Three.js’s angleTo() already accounts for the lengths of the input vectors when calculating the angle.</p><p>Therefore, this works:</p><pre>const angle = directionBA.angleTo(directionBC);</pre><p>And this also works for nonzero vectors:</p><pre>const angle = directionBA<br>  .clone()<br>  .normalize()<br>  .angleTo(directionBC.clone().normalize());</pre><p>Both should produce the same angle, apart from small floating-point differences.</p><p>So for today’s example, we don’t need to normalize manually.</p><p>However, we still need to check for zero-length vectors because they don’t have meaningful directions.</p><h3>13. What Is Happening Mathematically Behind angleTo()?</h3><p>I also wanted to understand a little of the mathematics behind this method.</p><p>The angle between two vectors can be calculated using the dot product.</p><p>The formula is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*JWUzXNEIm3APLqJiLbzUXw.png" /></figure><p>At first glance, that might look intimidating.</p><p>Let’s break it down.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*vzBsAxQod6g1dYj1BA2zkQ.png" /></figure><p>The dot product helps describe how much two vectors point in the same direction.</p><p>Dividing by their lengths removes the effect of how long the vectors are.</p><p>We then use inverse cosine to recover the angle.</p><p>For nonzero vectors, the formula becomes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RPGnIz4Q32eCEkm__F3_CQ.png" /></figure><p>Thankfully, I don’t need to implement all of this manually.</p><p>Three.js provides angleTo().</p><p>But understanding the idea helps me see that Three.js is not performing magic.</p><p>It is applying mathematics to vectors.</p><h3>14. Limitations of Our First Angle Measurement Tool</h3><p>Although our example works, it is still a beginner project.</p><p>There are a few important limitations.</p><p><strong>First, we select points on a flat floor.</strong></p><p>A professional measurement application might allow users to select points directly on a 3D mesh.</p><p><strong>Second, we display the angle as a number but don’t draw a curved angle arc.</strong></p><p>A visual arc would make it easier to understand which angle is being measured.</p><p><strong>Third, we only measure one angle at a time.</strong></p><p>A more advanced application could store multiple measurements, rename them, and allow users to edit or delete individual points.</p><p><strong>Fourth, our example does not support dragging measurement markers.</strong></p><p>That could be another useful feature later.</p><p><strong>Finally, </strong><strong>angleTo() returns an unsigned angle between 0° and 180°.</strong></p><p>It doesn’t tell us whether one direction rotates clockwise or anticlockwise around a chosen axis. Signed-angle measurement requires additional information, such as a reference plane or axis.</p><p>These limitations give us several interesting topics to explore as we continue learning.</p><h3>15. My Practice Challenge</h3><p>Before moving to the next lesson, I want to try a few things myself.</p><ol><li>Change the colours of the measurement points.</li><li>Change the thickness of the two lines.</li><li>Select three points that create an angle close to 90°.</li><li>Rotate the camera and observe whether the measurement changes.</li><li>Change the displayed result from one decimal place to two.</li><li>Modify the example to show a message when the selected points cannot define a valid angle.</li></ol><p>These exercises should help reinforce what I’ve learned.</p><h3>Conclusion</h3><p>Day 19 helped me understand another important part of 3D mathematics.</p><p>In Day 18, I learned how to measure the distance between two points.</p><p>Today, I learned how to measure the angle between three points.</p><p>The biggest lesson for me was understanding that an angle can be calculated by creating two direction vectors from a shared vertex.</p><p>Once I understood that, the Three.js code started to make much more sense.</p><p>I also learned how angleTo() works, why radians are used, how to convert radians into degrees, and how to display the calculated angle in a React Three Fiber scene.</p><p>What started as a simple lesson about vectors is gradually becoming a practical 3D measurement application.</p><p>And that’s what makes learning Three.js so interesting to me: small mathematical concepts can become useful interactive features.</p><h3>Coming Next — Day 20: Drawing Angle Arcs in 3D</h3><p>In the next lesson, I’ll take this angle measurement tool further.</p><p>Instead of displaying only the numerical angle, I’ll learn how to draw a curved arc between the two measurement lines.</p><p>This will help make the angle visually clearer and bring our tool closer to the measurement features found in professional 3D software.</p><p><strong>Thanks for following my Three.js learning journey!</strong></p><h3>References</h3><ul><li><a href="https://threejs.org/docs/#api/en/math/Vector3">Three.js Vector3 Documentation</a></li><li><a href="https://threejs.org/docs/#api/en/math/MathUtils">Three.js MathUtils Documentation</a></li><li><a href="https://r3f.docs.pmnd.rs/">React Three Fiber Documentation</a></li><li><a href="https://drei.docs.pmnd.rs/">Drei Documentation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=904cf2f1e1a8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 18 of Learning Three.js: Drawing Better Measurement Lines and Labels in React Three Fiber]]></title>
            <link>https://medium.com/@chiomsyndev/day-18-of-learning-three-js-drawing-better-measurement-lines-and-labels-in-react-three-fiber-3feb18d93779?source=rss-39943d331ca7------2</link>
            <guid isPermaLink="false">https://medium.com/p/3feb18d93779</guid>
            <category><![CDATA[3d-graphics]]></category>
            <category><![CDATA[threejs]]></category>
            <category><![CDATA[react-three-drei]]></category>
            <category><![CDATA[react-three-fiber]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Mirian Ezeamama]]></dc:creator>
            <pubDate>Thu, 05 Nov 2026 10:53:56 GMT</pubDate>
            <atom:updated>2026-11-05T10:53:56.493Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UXHOeKNs5e-2eVEBPI5umg.png" /></figure><p><em>How I learned to connect selected points, position distance labels, and display multiple measurements in a 3D scene.</em></p><p>On Day 17 of my Three.js learning journey, I built my first basic 3D distance measurement tool.</p><p>I learned how to select two points on a 3D model, calculate the distance between them using Vector3.distanceTo(), and connect them with a line.</p><p>But I started thinking about something.</p><p>What happens when I want to create several measurements?</p><p>How do I make the lines easy to see?</p><p>And how do I display the distance without placing the label somewhere random?</p><p>That’s what I wanted to explore today.</p><p>My goal was to make the measurement tool more useful and easier to understand.</p><h3>1. Why Do We Need Better Measurement Lines?</h3><p>In my previous example, I used a basic Three.js line:</p><pre>&lt;line geometry={geometry}&gt;<br>  &lt;lineBasicMaterial color=&quot;yellow&quot; /&gt;<br>&lt;/line&gt;</pre><p>This works, but I wanted something easier to manage.</p><p>I also wanted to control the line’s thickness and make it easier to display several measurements.</p><p>For this lesson, I decided to use Drei’s Line component.</p><p>First, I imported the components I needed:</p><pre>import {<br>  Line,<br>  Html,<br>  OrbitControls,<br>} from &quot;@react-three/drei&quot;;</pre><p>Here’s what each one does:</p><ul><li>Line draws a line between selected points.</li><li>Html displays HTML content inside a 3D scene.</li><li>OrbitControls allows me to rotate and inspect the scene.</li></ul><h3>2. Drawing a Line Using Drei’s Line Component</h3><p>Let’s start with two points:</p><pre>const pointA = [0, 0, 0];<br>const pointB = [2, 1, 0];</pre><p>We can connect them using:</p><pre>&lt;Line<br>  points={[pointA, pointB]}<br>  color=&quot;yellow&quot;<br>  lineWidth={3}<br>/&gt;</pre><p>The points property contains the positions we want to connect.</p><p>The color property controls the line colour.</p><p>The lineWidth property controls its thickness.</p><p>Drei’s Line uses a wide-line implementation, which makes it more flexible than an ordinary WebGL line.</p><p>One important thing to remember is that this line connects two positions directly. It does not follow the curved surface of a model.</p><h3>3. Finding the Middle of a Measurement Line</h3><p>Now I had a line connecting two points.</p><p>But where should I place the distance label?</p><p>I decided that the middle of the line would be a good starting point.</p><p>This position is called the midpoint.</p><p>A midpoint is simply the position halfway between two points.</p><p>For example:</p><pre>const pointA = new Vector3(0, 0, 0);<br>const pointB = new Vector3(4, 0, 0);</pre><p>The midpoint is:</p><pre>(2, 0, 0)</pre><p>We can calculate it using:</p><pre>const midpoint = new Vector3()<br>  .addVectors(pointA, pointB)<br>  .multiplyScalar(0.5);</pre><p>Let’s break this down.</p><p>new Vector3() creates a vector to store the result.</p><p>.addVectors(pointA, pointB) adds the coordinates of both points.</p><p>.multiplyScalar(0.5) multiplies each coordinate by one-half.</p><p>The result is the position halfway between the two points.</p><p>The formula is:</p><p>[<br>M=\frac{A+B}{2}<br>]</p><p>This is useful because we can use the midpoint to position our distance label.</p><h3>4. Displaying a Distance Label Using Html</h3><p>I learned something useful in Day 17: Drei’s Html component allows us to display ordinary HTML elements inside a 3D scene.</p><p>For example:</p><pre>&lt;Html position={[2, 0, 0]} center&gt;<br>  &lt;div&gt;<br>    Distance: 4.00 units<br>  &lt;/div&gt;<br>&lt;/Html&gt;</pre><p>The position property determines where the HTML element appears in the 3D scene.</p><p>The center property centres the HTML element around that position.</p><p>But instead of manually entering coordinates, I can use the midpoint we calculated earlier:</p><pre>&lt;Html position={midpoint.toArray()} center&gt;<br>  &lt;div&gt;<br>    Distance: {distance.toFixed(2)} units<br>  &lt;/div&gt;<br>&lt;/Html&gt;</pre><p>.toArray() converts the Vector3 into an array of three coordinates.</p><p>distance.toFixed(2) displays the distance to two decimal places.</p><p>For example:</p><pre>Distance: 4.00 units</pre><p>Now the label appears halfway along the measurement line.</p><h3>5. Storing Multiple Measurements</h3><p>So far, we’ve been working with only two points.</p><p>But what if I want to create several measurements?</p><p>For example:</p><ul><li>Measurement 1: Point A to Point B.</li><li>Measurement 2: Point C to Point D.</li><li>Measurement 3: Point E to Point F.</li></ul><p>Instead of storing only two positions, I can store an array of measurement objects.</p><p>Here’s an example:</p><pre>const measurements = [<br>  {<br>    start: [0, 0, 0],<br>    end: [2, 1, 0],<br>  },<br>  {<br>    start: [1, 0, 0],<br>    end: [1, 3, 0],<br>  },<br>];</pre><p>Each object contains a starting point and an ending point.</p><p>This gives me a better way to organise the measurements.</p><p>I can then use .map() to display each one:</p><pre>{measurements.map((measurement, index) =&gt; (<br>  &lt;MeasurementDisplay<br>    key={index}<br>    measurement={measurement}<br>  /&gt;<br>))}</pre><p>Each measurement can now have its own line, endpoint markers, distance calculation, and label.</p><h3>6. Creating a Reusable MeasurementDisplay Component</h3><p>I wanted to avoid repeating the same code every time I created a measurement.</p><p>So I created a component called MeasurementDisplay.</p><p>Its job is to display one complete measurement.</p><pre>type Point = [number, number, number];</pre><pre>type Measurement = {<br>  start: Point;<br>  end: Point;<br>};</pre><pre>function MeasurementDisplay({<br>  measurement,<br>}: {<br>  measurement: Measurement;<br>}) {<br>  const start = new Vector3(...measurement.start);<br>  const end = new Vector3(...measurement.end);</pre><pre>  const distance = start.distanceTo(end);</pre><pre>  const midpoint = new Vector3()<br>    .addVectors(start, end)<br>    .multiplyScalar(0.5);</pre><pre>  return (<br>    &lt;&gt;<br>      &lt;Line<br>        points={[measurement.start, measurement.end]}<br>        color=&quot;yellow&quot;<br>        lineWidth={3}<br>      /&gt;</pre><pre>      &lt;mesh position={measurement.start}&gt;<br>        &lt;sphereGeometry args={[0.06, 16, 16]} /&gt;<br>        &lt;meshBasicMaterial color=&quot;red&quot; /&gt;<br>      &lt;/mesh&gt;</pre><pre>      &lt;mesh position={measurement.end}&gt;<br>        &lt;sphereGeometry args={[0.06, 16, 16]} /&gt;<br>        &lt;meshBasicMaterial color=&quot;red&quot; /&gt;<br>      &lt;/mesh&gt;</pre><pre>      &lt;Html<br>        position={midpoint.toArray()}<br>        center<br>        style={{ pointerEvents: &quot;none&quot; }}<br>      &gt;<br>        &lt;div<br>          style={{<br>            background: &quot;#ffffff&quot;,<br>            color: &quot;#111111&quot;,<br>            padding: &quot;6px 10px&quot;,<br>            borderRadius: &quot;6px&quot;,<br>            fontSize: &quot;13px&quot;,<br>            fontWeight: &quot;bold&quot;,<br>            whiteSpace: &quot;nowrap&quot;,<br>          }}<br>        &gt;<br>          {distance.toFixed(2)} units<br>        &lt;/div&gt;<br>      &lt;/Html&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><p>Let’s look at the important parts.</p><p>First, I convert the stored coordinates into Vector3 objects:</p><pre>const start = new Vector3(...measurement.start);<br>const end = new Vector3(...measurement.end);</pre><p>The three dots are called the spread operator.</p><p>They take the three values from the array and pass them as separate arguments.</p><p>For example:</p><pre>new Vector3(...[1, 2, 3]);</pre><p>is the same as:</p><pre>new Vector3(1, 2, 3);</pre><p>Next, I calculate the distance:</p><pre>const distance = start.distanceTo(end);</pre><p>Then I calculate the midpoint:</p><pre>const midpoint = new Vector3()<br>  .addVectors(start, end)<br>  .multiplyScalar(0.5);</pre><p>Finally, I display the line, endpoint markers, and distance label.</p><p>I also added:</p><pre>style={{ pointerEvents: &quot;none&quot; }}</pre><p>This prevents the HTML label from intercepting mouse interactions intended for the 3D scene.</p><p>Now I have one reusable component that can display any measurement.</p><h3>7. Building a Scene That Supports Multiple Measurements</h3><p>Now let’s combine everything.</p><p>I want the user to click two points to create a measurement.</p><p>After that, the next two clicks should create another measurement without deleting the previous one.</p><p>Here’s the complete example:</p><pre>&quot;use client&quot;;</pre><pre>import { useState } from &quot;react&quot;;</pre><pre>import {<br>  Canvas,<br>  type ThreeEvent,<br>} from &quot;@react-three/fiber&quot;;</pre><pre>import {<br>  Html,<br>  Line,<br>  OrbitControls,<br>} from &quot;@react-three/drei&quot;;</pre><pre>import { Vector3 } from &quot;three&quot;;</pre><pre>type Point = [number, number, number];</pre><pre>type Measurement = {<br>  start: Point;<br>  end: Point;<br>};</pre><pre>function MeasurementDisplay({<br>  measurement,<br>}: {<br>  measurement: Measurement;<br>}) {<br>  const start = new Vector3(...measurement.start);<br>  const end = new Vector3(...measurement.end);</pre><pre>  const distance = start.distanceTo(end);</pre><pre>  const midpoint = new Vector3()<br>    .addVectors(start, end)<br>    .multiplyScalar(0.5);</pre><pre>  return (<br>    &lt;&gt;<br>      &lt;Line<br>        points={[measurement.start, measurement.end]}<br>        color=&quot;yellow&quot;<br>        lineWidth={3}<br>      /&gt;</pre><pre>      &lt;mesh position={measurement.start}&gt;<br>        &lt;sphereGeometry args={[0.06, 16, 16]} /&gt;<br>        &lt;meshBasicMaterial color=&quot;red&quot; /&gt;<br>      &lt;/mesh&gt;</pre><pre>      &lt;mesh position={measurement.end}&gt;<br>        &lt;sphereGeometry args={[0.06, 16, 16]} /&gt;<br>        &lt;meshBasicMaterial color=&quot;red&quot; /&gt;<br>      &lt;/mesh&gt;</pre><pre>      &lt;Html<br>        position={midpoint.toArray()}<br>        center<br>        style={{ pointerEvents: &quot;none&quot; }}<br>      &gt;<br>        &lt;div<br>          style={{<br>            background: &quot;#ffffff&quot;,<br>            color: &quot;#111111&quot;,<br>            padding: &quot;6px 10px&quot;,<br>            borderRadius: &quot;6px&quot;,<br>            fontSize: &quot;13px&quot;,<br>            fontWeight: &quot;bold&quot;,<br>            whiteSpace: &quot;nowrap&quot;,<br>          }}<br>        &gt;<br>          {distance.toFixed(2)} units<br>        &lt;/div&gt;<br>      &lt;/Html&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><pre>function MeasurementScene() {<br>  const [measurements, setMeasurements] =<br>    useState&lt;Measurement[]&gt;([]);</pre><pre>  const [pendingPoint, setPendingPoint] =<br>    useState&lt;Point | null&gt;(null);</pre><pre>  function handleClick(<br>    event: ThreeEvent&lt;MouseEvent&gt;<br>  ) {<br>    event.stopPropagation();</pre><pre>    const point: Point = [<br>      event.point.x,<br>      event.point.y,<br>      event.point.z,<br>    ];</pre><pre>    if (pendingPoint === null) {<br>      setPendingPoint(point);<br>      return;<br>    }</pre><pre>    setMeasurements((previous) =&gt; [<br>      ...previous,<br>      {<br>        start: pendingPoint,<br>        end: point,<br>      },<br>    ]);</pre><pre>    setPendingPoint(null);<br>  }</pre><pre>  return (<br>    &lt;&gt;<br>      &lt;mesh onClick={handleClick}&gt;<br>        &lt;boxGeometry args={[2, 2, 2]} /&gt;<br>        &lt;meshStandardMaterial color=&quot;orange&quot; /&gt;<br>      &lt;/mesh&gt;</pre><pre>      {measurements.map((measurement, index) =&gt; (<br>        &lt;MeasurementDisplay<br>          key={index}<br>          measurement={measurement}<br>        /&gt;<br>      ))}</pre><pre>      {pendingPoint &amp;&amp; (<br>        &lt;mesh position={pendingPoint}&gt;<br>          &lt;sphereGeometry args={[0.06, 16, 16]} /&gt;<br>          &lt;meshBasicMaterial color=&quot;lime&quot; /&gt;<br>        &lt;/mesh&gt;<br>      )}<br>    &lt;/&gt;<br>  );<br>}</pre><pre>export default function Scene() {<br>  const [resetKey, setResetKey] = useState(0);</pre><pre>  return (<br>    &lt;div&gt;<br>      &lt;button<br>        onClick={() =&gt; setResetKey((key) =&gt; key + 1)}<br>        style={{<br>          padding: &quot;8px 14px&quot;,<br>          marginBottom: &quot;10px&quot;,<br>          cursor: &quot;pointer&quot;,<br>        }}<br>      &gt;<br>        Clear measurements<br>      &lt;/button&gt;</pre><pre>      &lt;div style={{ height: 450 }}&gt;<br>        &lt;Canvas camera={{ position: [4, 3, 6] }}&gt;<br>          &lt;ambientLight intensity={0.5} /&gt;</pre><pre>          &lt;directionalLight<br>            position={[3, 5, 2]}<br>            intensity={2}<br>          /&gt;</pre><pre>          &lt;MeasurementScene key={resetKey} /&gt;</pre><pre>          &lt;OrbitControls /&gt;<br>        &lt;/Canvas&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><h3>Understanding the interaction</h3><p>There are two important pieces of state.</p><p>The first stores completed measurements:</p><pre>const [measurements, setMeasurements] =<br>  useState&lt;Measurement[]&gt;([]);</pre><p>The second stores the first point of an unfinished measurement:</p><pre>const [pendingPoint, setPendingPoint] =<br>  useState&lt;Point | null&gt;(null);</pre><p>Why do we need both?</p><p>Because a measurement is not complete after just one click.</p><p>We need somewhere to temporarily store the first selected point while waiting for the second click.</p><p>This is what pendingPoint does.</p><p>When the second point is selected, we save both points together:</p><pre>setMeasurements((previous) =&gt; [<br>  ...previous,<br>  {<br>    start: pendingPoint,<br>    end: point,<br>  },<br>]);</pre><p>Then we clear the temporary point:</p><pre>setPendingPoint(null);</pre><p>The next click can now start another measurement.</p><h3>Why is the first marker green?</h3><p>While we’re waiting for the second click, we display the first selected point as a green sphere.</p><p>This provides visual feedback.</p><p>Once the second point is selected, the completed measurement displays red endpoint markers and a yellow line.</p><h3>How does the Clear button work?</h3><p>We use:</p><pre>const [resetKey, setResetKey] = useState(0);</pre><p>When the button is clicked, the key changes.</p><p>React sees that MeasurementScene now has a different key and creates a fresh instance of that component.</p><p>Its measurements and pending point return to their initial empty states.</p><p>This is a simple way to reset the entire measurement scene.</p><p>In a larger application, I would probably keep the measurement state in a parent component and clear it directly. But this approach is useful for understanding component state.</p><h3>8. Things to Consider in a Real Measurement Application</h3><p>Our example is a good learning tool, but there are some important things to consider when building a more advanced application.</p><p><strong>1. The line and the measurement are different things.</strong></p><p>The line is only a visual representation.</p><p>The actual measurement comes from the two stored positions and the distance calculation.</p><p>We should preserve those original positions even if we later change how the line or label looks.</p><p><strong>2. Labels can overlap.</strong></p><p>When several measurements are close together, their labels may overlap.</p><p>A more advanced tool might allow users to drag labels or automatically adjust their positions.</p><p><strong>3. Visibility matters.</strong></p><p>A line can disappear against a similarly coloured surface.</p><p>We may eventually want contrasting colours, depth settings, or a different rendering technique to keep measurement lines readable.</p><p><strong>4. Model units still matter.</strong></p><p>The distance is calculated using the coordinates in the scene.</p><p>If we want millimeters or centimeters, we must know the original model units and account for any transformations.</p><h3>What I Learned on Day 18</h3><p>Today, I learned that:</p><ul><li>Drei’s Line component makes it easier to draw visible measurement lines.</li><li>A midpoint is the position halfway between two points.</li><li>Vector3.addVectors() adds two vectors.</li><li>Vector3.multiplyScalar() scales a vector.</li><li>Html can display distance labels inside a 3D scene.</li><li>.toArray() converts a Vector3 into an array.</li><li>Measurement objects can store multiple pairs of points.</li><li>React state can manage completed measurements and unfinished selections.</li><li>A reusable component makes it easier to display several measurements.</li></ul><p>But my biggest takeaway is this:</p><p><strong>A good 3D measurement tool needs more than an accurate calculation. It also needs clear visual feedback so that users can understand what they are measuring.</strong></p><p>That’s an important lesson as I continue learning Three.js and React Three Fiber.</p><h3>What’s Next?</h3><p>For Day 19, I want to explore <strong>measuring angles between three selected points in 3D space</strong>.</p><p>I already know how to select points and calculate distances.</p><p>Now I want to understand how to calculate the angle formed by two directions and display that angle visually.</p><p>One concept at a time.</p><h3>References</h3><ul><li><a href="https://threejs.org/docs/#api/en/math/Vector3">Three.js Vector3 Documentation</a></li><li><a href="https://drei.docs.pmnd.rs/shapes/line">Drei Line Documentation</a></li><li><a href="https://drei.docs.pmnd.rs/misc/html">Drei Html Documentation</a></li><li><a href="https://r3f.docs.pmnd.rs/">React Three Fiber Documentation</a></li></ul><p><em>Day 18 of my Three.js learning journey — learning in public, one concept at a time.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3feb18d93779" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 17 of Learning Three.js: Measuring Distance Between Two Points in 3D Space]]></title>
            <link>https://medium.com/@chiomsyndev/day-17-of-learning-three-js-measuring-distance-between-two-points-in-3d-space-abea7e704bbe?source=rss-39943d331ca7------2</link>
            <guid isPermaLink="false">https://medium.com/p/abea7e704bbe</guid>
            <category><![CDATA[react-three-fiber]]></category>
            <category><![CDATA[3d-graphics]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[threejs]]></category>
            <category><![CDATA[react-three-drei]]></category>
            <dc:creator><![CDATA[Mirian Ezeamama]]></dc:creator>
            <pubDate>Wed, 04 Nov 2026 13:31:43 GMT</pubDate>
            <atom:updated>2026-11-04T13:31:43.141Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UXHOeKNs5e-2eVEBPI5umg.png" /></figure><p><em>How I learned to calculate distances using Vector3, connect selected points with a line, and understand why measurement units matter.</em></p><p>On Day 16 of my Three.js learning journey, I learned about surface normals.</p><p>I used them to position markers slightly above a 3D surface instead of leaving them half-buried inside the model.</p><p>But after learning how to place markers, I started wondering:</p><p><strong>What if I want to measure the distance between two selected points?</strong></p><p>Imagine clicking two locations on a 3D model and seeing the distance between them.</p><p>That sounds like a useful feature for a 3D viewer.</p><p>Today, I decided to explore how to build a simple distance measurement tool using React Three Fiber.</p><h3>1. What Does Distance Mean in 3D?</h3><p>Let’s start with a simple example.</p><p>Imagine two points on a straight line.</p><p>Point A is at position 2.</p><p>Point B is at position 7.</p><p>The distance between them is 5 units.</p><p>But in 3D, positions have three coordinates: X, Y, and Z.</p><p>For example:</p><pre>const pointA = new Vector3(0, 0, 0);<br>const pointB = new Vector3(3, 4, 0);</pre><p>Point A is at the origin.</p><p>Point B is 3 units along X and 4 units along Y.</p><p>How far apart are they?</p><p>We can use the Pythagorean theorem.</p><p>The distance is:</p><p>[<br>\sqrt{3² + 4²} = 5<br>]</p><p>In 3D, we include the Z-axis as well.</p><p>But the good news is that Three.js already provides a method to calculate this for us.</p><h3>2. Understanding distanceTo()</h3><p>Three.js provides a method called .distanceTo().</p><p>Here’s an example:</p><pre>import { Vector3 } from &quot;three&quot;;</pre><pre>const pointA = new Vector3(0, 0, 0);<br>const pointB = new Vector3(3, 4, 0);</pre><pre>const distance = pointA.distanceTo(pointB);</pre><pre>console.log(distance); // 5</pre><p>Let’s break it down.</p><p>new Vector3() creates a vector containing X, Y, and Z coordinates.</p><p>pointA represents the first position.</p><p>pointB represents the second position.</p><p>Then:</p><pre>pointA.distanceTo(pointB);</pre><p>calculates the straight-line distance between them.</p><p>The result is a number.</p><p>In this example, the result is 5.</p><p>One thing I learned is that .distanceTo() doesn&#39;t return another vector.</p><p>It returns a single number representing the distance.</p><h3>3. Distance Versus Displacement</h3><p>Remember when we learned about vector subtraction?</p><p>We used:</p><pre>const displacement = pointB.clone().sub(pointA);</pre><p>This calculates the displacement vector from Point A to Point B.</p><p>For example:</p><pre>pointA = (0, 0, 0)<br>pointB = (3, 4, 0)</pre><p>The displacement is:</p><pre>(3, 4, 0)</pre><p>That’s a vector.</p><p>But:</p><pre>pointA.distanceTo(pointB)</pre><p>returns:</p><pre>5</pre><p>That’s a number.</p><p>So the difference is simple.</p><p><strong>Displacement tells me how to get from one point to another. Distance tells me how far apart they are.</strong></p><p>And the length of the displacement vector equals the distance between the points.</p><pre>const displacement = pointB.clone().sub(pointA);</pre><pre>console.log(displacement.length()); // 5<br>console.log(pointA.distanceTo(pointB)); // 5</pre><p>Both give the same distance.</p><h3>4. Connecting Two Points with a Line</h3><p>Now that I can calculate distance, I want to make the measurement visible.</p><p>Imagine clicking two points on a box.</p><p>I want to draw a line connecting them.</p><p>Three.js provides a way to create line geometry using BufferGeometry.</p><p>Here’s a simple example:</p><pre>import { BufferGeometry, Vector3 } from &quot;three&quot;;</pre><pre>const pointA = new Vector3(0, 0, 0);<br>const pointB = new Vector3(3, 0, 0);</pre><pre>const geometry = new BufferGeometry().setFromPoints([<br>  pointA,<br>  pointB,<br>]);</pre><p>Let’s understand it.</p><p>BufferGeometry stores geometric data.</p><p>setFromPoints() creates position data from an array of Vector3 objects.</p><p>Here, we provide two points.</p><p>That gives us the geometry for a straight line segment.</p><p>We can render it using:</p><pre>&lt;line geometry={geometry}&gt;<br>  &lt;lineBasicMaterial color=&quot;yellow&quot; /&gt;<br>&lt;/line&gt;</pre><p>Notice that we’re using &lt;line&gt;, not &lt;mesh&gt;.</p><p>A mesh renders surfaces.</p><p>A line renders line segments.</p><p>This will create a yellow line connecting the two points.</p><h3>5. Building My First Distance Measurement Tool</h3><p>Now let’s combine what we’ve learned.</p><p>We’ll create a box that allows us to click two points.</p><p>After selecting the second point, we’ll calculate the distance and draw a line between them.</p><pre>&quot;use client&quot;;</pre><pre>import { useMemo, useState } from &quot;react&quot;;<br>import { Canvas, type ThreeEvent } from &quot;@react-three/fiber&quot;;<br>import { OrbitControls, Html } from &quot;@react-three/drei&quot;;<br>import { BufferGeometry, Vector3 } from &quot;three&quot;;</pre><pre>type Point = [number, number, number];</pre><pre>function MeasurementLine({ points }: { points: Point[] }) {<br>  const geometry = useMemo(() =&gt; {<br>    if (points.length !== 2) return null;</pre><pre>    return new BufferGeometry().setFromPoints([<br>      new Vector3(...points[0]),<br>      new Vector3(...points[1]),<br>    ]);<br>  }, [points]);</pre><pre>  if (!geometry) return null;</pre><pre>  return (<br>    &lt;line geometry={geometry}&gt;<br>      &lt;lineBasicMaterial color=&quot;yellow&quot; /&gt;<br>    &lt;/line&gt;<br>  );<br>}</pre><pre>function MeasurementBox() {<br>  const [points, setPoints] = useState&lt;Point[]&gt;([]);</pre><pre>  function handleClick(event: ThreeEvent&lt;MouseEvent&gt;) {<br>    event.stopPropagation();</pre><pre>    const point = event.point;</pre><pre>    setPoints((previous) =&gt; {<br>      if (previous.length === 2) {<br>        return [[point.x, point.y, point.z]];<br>      }</pre><pre>      return [...previous, [point.x, point.y, point.z]];<br>    });<br>  }</pre><pre>  const distance =<br>    points.length === 2<br>      ? new Vector3(...points[0]).distanceTo(<br>          new Vector3(...points[1])<br>        )<br>      : null;</pre><pre>  return (<br>    &lt;&gt;<br>      &lt;mesh onClick={handleClick}&gt;<br>        &lt;boxGeometry args={[2, 2, 2]} /&gt;<br>        &lt;meshStandardMaterial color=&quot;orange&quot; /&gt;<br>      &lt;/mesh&gt;</pre><pre>      {points.map((position, index) =&gt; (<br>        &lt;mesh key={index} position={position}&gt;<br>          &lt;sphereGeometry args={[0.06, 16, 16]} /&gt;<br>          &lt;meshBasicMaterial color=&quot;red&quot; /&gt;<br>        &lt;/mesh&gt;<br>      ))}</pre><pre>      &lt;MeasurementLine points={points} /&gt;</pre><pre>      {distance !== null &amp;&amp; (<br>        &lt;Html position={[0, 2, 0]} center&gt;<br>          &lt;div<br>            style={{<br>              background: &quot;white&quot;,<br>              padding: &quot;8px&quot;,<br>              borderRadius: &quot;6px&quot;,<br>              color: &quot;black&quot;,<br>            }}<br>          &gt;<br>            Distance: {distance.toFixed(2)} units<br>          &lt;/div&gt;<br>        &lt;/Html&gt;<br>      )}<br>    &lt;/&gt;<br>  );<br>}</pre><pre>export default function Scene() {<br>  return (<br>    &lt;div style={{ height: 450 }}&gt;<br>      &lt;Canvas camera={{ position: [4, 3, 6] }}&gt;<br>        &lt;ambientLight intensity={0.5} /&gt;<br>        &lt;directionalLight position={[3, 5, 2]} intensity={2} /&gt;</pre><pre>        &lt;MeasurementBox /&gt;</pre><pre>        &lt;OrbitControls /&gt;<br>      &lt;/Canvas&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>Let’s understand the important parts.</p><p>First:</p><pre>const [points, setPoints] = useState&lt;Point[]&gt;([]);</pre><p>This stores the selected points.</p><p>We start with an empty array.</p><p>When I click the box, React Three Fiber gives me the intersection point.</p><p>I then store its X, Y, and Z coordinates.</p><p>But I only want two points at a time.</p><p>So I use:</p><pre>setPoints((previous) =&gt; {<br>  if (previous.length === 2) {<br>    return [[point.x, point.y, point.z]];<br>  }</pre><pre>  return [...previous, [point.x, point.y, point.z]];<br>});</pre><p>This means:</p><p>If I already have two points, start a new measurement.</p><p>Otherwise, add the new point.</p><p>So the behavior is:</p><p>First click: Select Point A.</p><p>Second click: Select Point B and calculate the distance.</p><p>Third click: Start a new measurement.</p><p>Fourth click: Complete the new measurement.</p><p>Next, I calculate the distance:</p><pre>const distance =<br>  points.length === 2<br>    ? new Vector3(...points[0]).distanceTo(<br>        new Vector3(...points[1])<br>      )<br>    : null;</pre><p>The important part is .distanceTo().</p><p>It calculates the straight-line distance between the two selected points.</p><p>The ... syntax spreads the three numbers from the array into the Vector3 constructor.</p><p>So:</p><pre>new Vector3(...[1, 2, 3])</pre><p>is equivalent to:</p><pre>new Vector3(1, 2, 3)</pre><p>Next, I render a line connecting the points.</p><p>And finally, I use Drei’s Html component to display the distance value inside the scene.</p><p>For example:</p><pre>Distance: 2.45 units</pre><p>That’s my first simple 3D distance measurement tool!</p><h3>6. Why Measurement Units Matter</h3><p>This is one of the most important things I learned today.</p><p>Three.js can calculate the distance between two points.</p><p>But it doesn’t automatically know whether the result represents millimeters, centimeters, or meters.</p><p>For example:</p><pre>const distance = pointA.distanceTo(pointB);</pre><p>might return:</p><pre>2.5</pre><p>But what does 2.5 mean?</p><p>That depends on the model’s coordinate system and units.</p><p>If the model uses millimeters, the result can be interpreted as millimeters.</p><p>If it uses meters, the result can be interpreted as meters.</p><p>But Three.js doesn’t assign those units automatically.</p><p>I need to know what units the model uses.</p><h3>Example</h3><p>Suppose I know the model coordinates are in millimeters.</p><p>If the measured distance is:</p><pre>125</pre><p>then the physical distance is 125 mm.</p><p>To convert that to centimeters:</p><pre>const centimeters = 125 / 10;</pre><p>The result is 12.5 cm.</p><p>But there’s another important issue.</p><p>What if the model was scaled after loading?</p><p>For example, suppose I normalized a large model to fit inside a small viewing area.</p><p>The coordinates used for rendering might no longer match the original physical coordinates.</p><p>In that case, I need to account for the scale transformation before interpreting the measurement physically.</p><p>This is especially important in applications that require accurate measurements.</p><h3>7. Straight-Line Distance Versus Surface Distance</h3><p>Another important thing I learned is that .distanceTo() calculates straight-line distance.</p><p>It doesn’t calculate distance along a curved surface.</p><p>Imagine two points on opposite sides of a curved object.</p><p>The straight-line distance is the shortest direct distance through 3D space.</p><p>But the distance along the surface follows the shape of the object.</p><p>These can be very different.</p><p>For today’s lesson, I’m focusing on straight-line measurements.</p><p>Calculating distances along a surface requires additional geometry algorithms.</p><p>That’s something I want to explore later.</p><h3>8. Why This Matters in Real Applications</h3><p>Distance measurement is useful in many 3D applications.</p><p>For example, a designer might want to measure the distance between two selected points on a model.</p><p>A 3D viewer might allow users to inspect object dimensions.</p><p>And a measurement application might use selected landmarks to calculate distances.</p><p>But reliable measurements require more than simply calling .distanceTo().</p><p>We also need to consider coordinate systems, model units, transformations, and geometry accuracy.</p><p>For now, I’m happy that I understand the basic calculation.</p><p>I can select two points, connect them with a line, and display their straight-line distance.</p><p>That’s a useful building block.</p><h3>What I Learned on Day 17</h3><p>Today, I learned that:</p><ul><li>Vector3.distanceTo() calculates the straight-line distance between two points.</li><li>Distance is a number, while displacement is a vector.</li><li>The length of a displacement vector equals the distance between its endpoints.</li><li>BufferGeometry.setFromPoints() can create line geometry.</li><li>&lt;line&gt; renders a line segment between points.</li><li>React state can store two selected measurement points.</li><li>Drei’s Html component can display a measurement label.</li><li>Three.js does not automatically assign physical units to geometry.</li><li>Straight-line distance is different from distance along a curved surface.</li></ul><p>But my biggest takeaway is this:</p><p><strong>Calculating distance is easy. Interpreting that distance correctly requires understanding the model’s units and transformations.</strong></p><p>And that’s something I’ll keep in mind as I continue learning.</p><h3>What’s Next?</h3><p>For Day 18, I want to explore <strong>drawing lines and visualizing measurements more clearly in React Three Fiber</strong>.</p><p>Now that I can calculate distances, I want to improve how measurements appear in the scene.</p><p>I’ll explore how to position labels near measurement lines, how to make lines easier to see, and how to manage multiple measurements.</p><p>One concept at a time.</p><h3>References</h3><ul><li><a href="https://threejs.org/docs/#api/en/math/Vector3">Three.js Vector3 Documentation</a></li><li><a href="https://threejs.org/docs/#api/en/core/BufferGeometry">Three.js BufferGeometry Documentation</a></li><li><a href="https://r3f.docs.pmnd.rs/">React Three Fiber Documentation</a></li><li><a href="https://github.com/pmndrs/drei">Drei Documentation</a></li></ul><p><em>Day 17 of my Three.js learning journey — learning in public, one concept at a time.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=abea7e704bbe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 16 of Learning Three.js: Understanding Surface Normals in React Three Fiber]]></title>
            <link>https://medium.com/@chiomsyndev/day-16-of-learning-three-js-understanding-surface-normals-in-react-three-fiber-e963727fe07b?source=rss-39943d331ca7------2</link>
            <guid isPermaLink="false">https://medium.com/p/e963727fe07b</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[3d-graphics]]></category>
            <category><![CDATA[react-three-fiber]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[threejs]]></category>
            <dc:creator><![CDATA[Mirian Ezeamama]]></dc:creator>
            <pubDate>Tue, 03 Nov 2026 10:10:49 GMT</pubDate>
            <atom:updated>2026-11-03T10:10:49.899Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UXHOeKNs5e-2eVEBPI5umg.png" /></figure><p><em>How I learned to understand which direction a 3D surface is facing and use that information to place markers correctly.</em></p><p>On Day 15 of my Three.js learning journey, I learned how to click a 3D model and place markers on its surface.</p><p>I used raycasting to find the clicked position and stored that position using React state.</p><p>But I noticed something.</p><p>Sometimes my markers were half-buried inside the box.</p><p>At first, I wondered whether I was placing them at the wrong coordinates.</p><p>But the problem was actually much simpler.</p><p>I was placing the center of each sphere exactly on the surface.</p><p>Since the sphere has a radius, part of it naturally extends inside the model.</p><p>That led me to today’s topic:</p><p><strong>Surface normals.</strong></p><h3>1. What Is a Surface Normal?</h3><p>A surface normal is a vector that points perpendicular to a surface.</p><p>Imagine a flat table.</p><p>If I place a pencil on the table so that it stands straight up, the pencil points in a direction perpendicular to the table.</p><p>That’s similar to a surface normal.</p><p>But normals don’t always point upward.</p><p>A vertical wall has a sideways normal.</p><p>A sloping surface has a diagonal normal.</p><p>The direction depends on the surface’s orientation.</p><p>This is important because it tells us which way a surface is facing.</p><h3>2. A Normal Is a Vector3</h3><p>We’ve already learned about Vector3 in earlier lessons.</p><p>A Vector3 contains three numbers: X, Y, and Z.</p><p>It can represent a position or a direction.</p><p>A surface normal is a direction vector.</p><p>For example:</p><pre>const normal = new THREE.Vector3(0, 1, 0);</pre><p>This points upward along the positive Y-axis.</p><p>Another example:</p><pre>const normal = new THREE.Vector3(1, 0, 0);</pre><p>This points along the positive X-axis.</p><p>And:</p><pre>const normal = new THREE.Vector3(0, 0, -1);</pre><p>points along the negative Z-axis.</p><p>Surface normals are usually represented as unit vectors.</p><p>That means their length is 1.</p><p>This makes them useful for calculating directions and offsets.</p><h3>3. Why Do We Need Surface Normals?</h3><p>Surface normals are useful for several reasons.</p><p>First, they help with lighting.</p><p>When light reaches a surface, the renderer needs to know which direction the surface faces.</p><p>Second, normals help us position objects relative to surfaces.</p><p>For example, if I want to place a marker slightly above a model, I need to know which direction points away from the surface.</p><p>Third, normals can help orient objects.</p><p>If I want an arrow to point outward from a selected surface, the normal can help determine its direction.</p><p>Today, I’m focusing on marker placement.</p><h3>4. Understanding the Marker Problem</h3><p>Let’s revisit our Day 15 example.</p><p>We clicked a surface and obtained:</p><pre>const point = event.point;</pre><p>Then we placed a marker at that point.</p><pre>&lt;mesh position={[point.x, point.y, point.z]}&gt;<br>  &lt;sphereGeometry args={[0.08, 16, 16]} /&gt;<br>  &lt;meshBasicMaterial color=&quot;red&quot; /&gt;<br>&lt;/mesh&gt;</pre><p>The problem is that the marker’s position represents its center.</p><p>So if the marker has a radius of 0.08, half of it may extend inside the model.</p><p>What I actually want is to move the marker slightly outward.</p><p>To do that, I need the surface normal.</p><p>The idea is simple:</p><p><strong>New marker position = clicked point + normal × offset</strong></p><p>The normal tells us which direction to move.</p><p>The offset tells us how far to move.</p><h3>5. Getting the Surface Normal from Raycasting</h3><p>React Three Fiber gives us information about the intersected face.</p><p>For triangle-based meshes, we can access:</p><pre>event.face?.normal</pre><p>The question mark means the face might not exist.</p><p>So we should check before using it.</p><pre>if (!event.face) return;</pre><p>Then we can access the normal:</p><pre>const normal = event.face.normal;</pre><p>But there’s something important.</p><p>event.face.normal is in the mesh&#39;s local coordinate system.</p><p>Meanwhile, event.point is in world coordinates.</p><p>That means we cannot always use them together directly.</p><p>If the mesh is rotated, its local normal might point in a different direction from the corresponding world-space normal.</p><p>So we need to convert it.</p><h3>6. Converting the Normal into World Space</h3><p>Three.js provides a useful tool called a normal matrix.</p><p>A normal matrix helps transform surface normals correctly, even when an object has nonuniform scaling.</p><p>Here’s the code:</p><pre>import { Matrix3 } from &quot;three&quot;;</pre><pre>const normalMatrix = new Matrix3().getNormalMatrix(<br>  event.object.matrixWorld<br>);</pre><pre>const worldNormal = event.face.normal<br>  .clone()<br>  .applyMatrix3(normalMatrix)<br>  .normalize();</pre><p>Let’s understand it step by step.</p><p>Matrix3 represents a 3-by-3 matrix.</p><p>getNormalMatrix() calculates the transformation needed for normals.</p><p>event.object.matrixWorld contains the object&#39;s world transformation.</p><p>.clone() creates a copy of the original normal.</p><p>.applyMatrix3(normalMatrix) transforms the normal into world space.</p><p>And .normalize() makes sure the resulting direction has a length of 1.</p><p>Now I have a world-space normal that I can use with event.point.</p><h3>7. Moving the Marker Outward</h3><p>Once I have the world-space normal, I can calculate the marker position.</p><pre>const markerPosition = event.point<br>  .clone()<br>  .addScaledVector(worldNormal, 0.08);</pre><p>Let’s break it down.</p><p>First:</p><pre>event.point.clone()</pre><p>creates a copy of the clicked position.</p><p>Then:</p><pre>.addScaledVector(worldNormal, 0.08)</pre><p>adds the normal multiplied by 0.08.</p><p>This moves the marker 0.08 world units outward from the surface.</p><p>Since my sphere has a radius of 0.08 world units in this example, its center is now one radius away from the surface.</p><p>That should prevent the sphere from being half-buried.</p><h3>8. My Complete Example</h3><p>Now let’s combine everything into a React Three Fiber scene.</p><pre>&quot;use client&quot;;</pre><pre>import { useState } from &quot;react&quot;;<br>import { Canvas, type ThreeEvent } from &quot;@react-three/fiber&quot;;<br>import { OrbitControls } from &quot;@react-three/drei&quot;;<br>import { Matrix3 } from &quot;three&quot;;</pre><pre>type Point = [number, number, number];</pre><pre>function MarkableBox() {<br>  const [markers, setMarkers] = useState&lt;Point[]&gt;([]);</pre><pre>  function handleClick(event: ThreeEvent&lt;MouseEvent&gt;) {<br>    event.stopPropagation();</pre><pre>    if (!event.face) return;</pre><pre>    event.object.updateWorldMatrix(true, false);</pre><pre>    const normalMatrix = new Matrix3().getNormalMatrix(<br>      event.object.matrixWorld<br>    );</pre><pre>    const worldNormal = event.face.normal<br>      .clone()<br>      .applyMatrix3(normalMatrix)<br>      .normalize();</pre><pre>    const markerPosition = event.point<br>      .clone()<br>      .addScaledVector(worldNormal, 0.08);</pre><pre>    setMarkers((previous) =&gt; [<br>      ...previous,<br>      [<br>        markerPosition.x,<br>        markerPosition.y,<br>        markerPosition.z,<br>      ],<br>    ]);<br>  }</pre><pre>  return (<br>    &lt;&gt;<br>      &lt;mesh onClick={handleClick}&gt;<br>        &lt;boxGeometry args={[2, 2, 2]} /&gt;<br>        &lt;meshStandardMaterial color=&quot;orange&quot; /&gt;<br>      &lt;/mesh&gt;</pre><pre>      {markers.map((position, index) =&gt; (<br>        &lt;mesh key={index} position={position}&gt;<br>          &lt;sphereGeometry args={[0.08, 16, 16]} /&gt;<br>          &lt;meshBasicMaterial color=&quot;red&quot; /&gt;<br>        &lt;/mesh&gt;<br>      ))}<br>    &lt;/&gt;<br>  );<br>}</pre><pre>export default function Scene() {<br>  return (<br>    &lt;div style={{ height: 450 }}&gt;<br>      &lt;Canvas camera={{ position: [4, 3, 6] }}&gt;<br>        &lt;ambientLight intensity={0.5} /&gt;</pre><pre>        &lt;directionalLight<br>          position={[3, 5, 2]}<br>          intensity={2}<br>        /&gt;</pre><pre>        &lt;MarkableBox /&gt;</pre><pre>        &lt;OrbitControls /&gt;<br>      &lt;/Canvas&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>Here’s what happens when I click the box.</p><p>First, React Three Fiber calculates the raycast intersection.</p><p>Then event.point gives me the clicked surface position.</p><p>event.face.normal gives me the face normal in local coordinates.</p><p>I transform that normal into world space using a normal matrix.</p><p>Then I move the clicked point slightly outward along that normal.</p><p>Finally, I store the new marker position and render a red sphere there.</p><p>That’s how the marker is placed outside the surface.</p><h3>9. What Happens If the Box Is Rotated?</h3><p>Let’s say I rotate the box:</p><pre>&lt;mesh<br>  rotation={[0, Math.PI / 4, 0]}<br>  onClick={handleClick}<br>&gt;</pre><p>This rotates the box by 45 degrees around the Y-axis.</p><p>If I used the local normal directly with the world-space intersection point, the marker could move in the wrong direction.</p><p>But because I’m converting the normal into world space, the offset follows the rotated surface.</p><p>This is another example of why coordinate systems matter so much in 3D development.</p><h3>10. Surface Normals and Lighting</h3><p>I also learned that surface normals play an important role in lighting.</p><p>Imagine shining a directional light onto a box.</p><p>The renderer needs to know which direction each surface faces.</p><p>A surface facing the light generally receives more direct illumination.</p><p>A surface facing away receives less.</p><p>This is one reason why the same material can appear bright on one face and dark on another.</p><p>I also discovered that there are different kinds of normals.</p><p>A face normal is perpendicular to a triangle.</p><p>A vertex normal is associated with a vertex and can be interpolated across a surface for smooth shading.</p><p>For today’s marker example, I’m using the intersected face’s normal.</p><p>But for more advanced applications, I’ll need to understand when to use face normals and when to use interpolated normals.</p><h3>11. Why This Matters in Real Applications</h3><p>Surface normals are useful in many 3D applications.</p><p>They can help position markers on a model.</p><p>They can help orient arrows and other objects.</p><p>They are important for lighting and shading.</p><p>And they can help determine the orientation of a selected surface.</p><p>For example, in a 3D measurement application, a user might click a model to place a reference marker.</p><p>The surface normal could help position a visible marker slightly above the surface.</p><p>Of course, the exact surface point should still be preserved separately if it will be used for measurement.</p><p>The outward offset is only for visualization.</p><p>That’s an important distinction.</p><h3>What I Learned on Day 16</h3><p>Today, I learned that:</p><ul><li>A surface normal is perpendicular to a surface.</li><li>Normals are represented using vectors.</li><li>Normals help with lighting, orientation, and surface offsets.</li><li>event.face.normal provides the intersected triangle&#39;s local-space normal.</li><li>event.point provides the world-space intersection point.</li><li>A normal matrix converts local normals into world space correctly.</li><li>.clone() prevents unwanted changes to the original vector.</li><li>.addScaledVector() lets us move a point along a direction.</li><li>We can use normals to position markers slightly outside a model.</li></ul><p>But my biggest takeaway is this:</p><p><strong>A surface point tells me where something is. A surface normal tells me which direction the surface is facing.</strong></p><p>And when I combine the two, I can position objects relative to a 3D surface much more accurately.</p><h3>What’s Next?</h3><p>For Day 17, I want to explore <strong>measuring distances between two selected points in 3D space</strong>.</p><p>Now that I can click a surface and place markers, I want to understand how to calculate the distance between two points using Vector3.distanceTo().</p><p>I’ll also explore why model units matter when interpreting the result.</p><p>One concept at a time.</p><h3>References</h3><ul><li><a href="https://threejs.org/docs/#api/en/math/Vector3">Three.js Vector3 Documentation</a></li><li><a href="https://threejs.org/docs/#api/en/math/Matrix3">Three.js Matrix3 Documentation</a></li><li><a href="https://threejs.org/docs/#api/en/core/Raycaster">Three.js Raycaster Documentation</a></li><li><a href="https://r3f.docs.pmnd.rs/api/events">React Three Fiber Events Documentation</a></li></ul><p><em>Day 16 of my Three.js learning journey — learning in public, one concept at a time.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e963727fe07b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 15 of Learning Three.js: Placing Markers on 3D Surfaces Using Raycasting]]></title>
            <link>https://medium.com/@chiomsyndev/day-15-of-learning-three-js-placing-markers-on-3d-surfaces-using-raycasting-0d6405292345?source=rss-39943d331ca7------2</link>
            <guid isPermaLink="false">https://medium.com/p/0d6405292345</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react-three-fiber]]></category>
            <category><![CDATA[3d-graphics]]></category>
            <category><![CDATA[threejs]]></category>
            <dc:creator><![CDATA[Mirian Ezeamama]]></dc:creator>
            <pubDate>Mon, 02 Nov 2026 12:51:35 GMT</pubDate>
            <atom:updated>2026-11-02T12:51:35.575Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UXHOeKNs5e-2eVEBPI5umg.png" /></figure><p><em>How I learned to place markers exactly where I click a 3D object — and why local and world coordinates matter.</em></p><p>On Day 14 of my Three.js learning journey, I learned how to make 3D objects clickable.</p><p>I used onClick to detect clicks, useState to change a box&#39;s color, and raycasting to understand which object I clicked.</p><p>But one thing caught my attention.</p><p>React Three Fiber gives us something called event.point.</p><p>This tells us where the ray intersects the surface of the object.</p><p>And that made me wonder:</p><p><strong>What if I could click a 3D model and place a small marker exactly where I clicked?</strong></p><p>That sounds simple, but it introduces an important concept: coordinate systems.</p><p>Today, I decided to explore how to place markers on 3D surfaces and understand the difference between world and local coordinates.</p><h3>1. What Is a 3D Marker?</h3><p>A marker is simply an object that identifies a particular position.</p><p>Imagine opening a 3D model and clicking a point you want to remember.</p><p>You could place a small sphere at that location.</p><p>Later, you might use that marker as a reference for a measurement or another operation.</p><p>For today’s lesson, I’ll use a small red sphere.</p><p>The sphere itself is easy to create.</p><p>The interesting part is knowing where to place it.</p><h3>2. Understanding event.point</h3><p>Let’s start with something we learned yesterday.</p><pre>&lt;mesh<br>  onClick={(event) =&gt; {<br>    console.log(event.point);<br>  }}<br>&gt;</pre><p>When we click a mesh, React Three Fiber provides information about the intersection.</p><p>One useful property is event.point.</p><p>This is a Three.js Vector3.</p><p>Remember that a Vector3 contains three numbers: X, Y, and Z.</p><p>For example, a clicked position might be:</p><pre>Vector3 {<br>  x: 0.5,<br>  y: 0.2,<br>  z: 1<br>}</pre><p>These values represent a position in world coordinates.</p><p>That means they describe the point relative to the overall scene.</p><p>But that doesn’t always mean we can use the values directly as a child object’s local position.</p><p>We’ll come back to that.</p><h3>3. Creating My First Marker</h3><p>Before placing markers with raycasting, I wanted to create one manually.</p><p>Here’s the code:</p><pre>&lt;mesh position={[0, 1, 0]}&gt;<br>  &lt;sphereGeometry args={[0.08, 16, 16]} /&gt;<br>  &lt;meshBasicMaterial color=&quot;red&quot; /&gt;<br>&lt;/mesh&gt;</pre><p>Let’s understand it.</p><p>mesh creates the object.</p><p>position tells Three.js where to place it.</p><p>sphereGeometry creates a sphere.</p><p>And meshBasicMaterial gives it a red color that doesn&#39;t depend on scene lighting.</p><p>The interesting part is:</p><pre>&lt;sphereGeometry args={[0.08, 16, 16]} /&gt;</pre><p>The first number is the radius.</p><p>So our sphere has a radius of 0.08 units.</p><p>The next two numbers control the geometry’s horizontal and vertical segments.</p><p>More segments generally make the sphere look smoother, but they also create more polygons.</p><p>For our small marker, 16 segments in each direction are enough.</p><h3>4. Placing a Marker When I Click</h3><p>Now let’s make the marker appear where I click the box.</p><p>I’ll start with a simple example that stores only one marker.</p><pre>&quot;use client&quot;;</pre><pre>import { useState } from &quot;react&quot;;<br>import { Canvas, type ThreeEvent } from &quot;@react-three/fiber&quot;;<br>import { OrbitControls } from &quot;@react-three/drei&quot;;</pre><pre>type Point = [number, number, number];</pre><pre>function ClickableBox() {<br>  const [marker, setMarker] = useState&lt;Point | null&gt;(null);</pre><pre>  function handleClick(event: ThreeEvent&lt;MouseEvent&gt;) {<br>    event.stopPropagation();</pre><pre>    const point = event.point;</pre><pre>    setMarker([point.x, point.y, point.z]);<br>  }</pre><pre>  return (<br>    &lt;&gt;<br>      &lt;mesh onClick={handleClick}&gt;<br>        &lt;boxGeometry args={[2, 2, 2]} /&gt;<br>        &lt;meshStandardMaterial color=&quot;orange&quot; /&gt;<br>      &lt;/mesh&gt;</pre><pre>      {marker &amp;&amp; (<br>        &lt;mesh position={marker}&gt;<br>          &lt;sphereGeometry args={[0.08, 16, 16]} /&gt;<br>          &lt;meshBasicMaterial color=&quot;red&quot; /&gt;<br>        &lt;/mesh&gt;<br>      )}<br>    &lt;/&gt;<br>  );<br>}</pre><pre>export default function Scene() {<br>  return (<br>    &lt;div style={{ height: 450 }}&gt;<br>      &lt;Canvas camera={{ position: [4, 3, 6] }}&gt;<br>        &lt;ambientLight intensity={0.5} /&gt;<br>        &lt;directionalLight position={[3, 5, 2]} intensity={2} /&gt;</pre><pre>        &lt;ClickableBox /&gt;</pre><pre>        &lt;OrbitControls /&gt;<br>      &lt;/Canvas&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>Now let’s break down the important parts.</p><p>First:</p><pre>type Point = [number, number, number];</pre><p>This creates a TypeScript type for an array containing three numbers.</p><p>We’ll use those numbers to represent X, Y, and Z.</p><p>Next:</p><pre>const [marker, setMarker] = useState&lt;Point | null&gt;(null);</pre><p>This creates state for the marker.</p><p>Point | null means the value can be either a three-number position or null.</p><p>Why null?</p><p>Because when the scene first loads, I haven’t clicked anywhere.</p><p>There is no marker yet.</p><p>Next:</p><pre>function handleClick(event: ThreeEvent&lt;MouseEvent&gt;) {</pre><p>This defines the function that handles the click.</p><p>The ThreeEvent&lt;MouseEvent&gt; type tells TypeScript that we&#39;re receiving a React Three Fiber mouse event.</p><p>Then:</p><pre>const point = event.point;</pre><p>gets the world-space intersection point.</p><p>And:</p><pre>setMarker([point.x, point.y, point.z]);</pre><p>stores its coordinates.</p><p>Finally:</p><pre>{marker &amp;&amp; (<br>  &lt;mesh position={marker}&gt;<br>    &lt;sphereGeometry args={[0.08, 16, 16]} /&gt;<br>    &lt;meshBasicMaterial color=&quot;red&quot; /&gt;<br>  &lt;/mesh&gt;<br>)}</pre><p>renders the marker only when a position exists.</p><p>Before clicking, nothing appears.</p><p>After clicking, a small red sphere appears at the intersection point.</p><p>And every new click moves the marker to a new position.</p><p>That’s my first surface marker!</p><h3>5. Placing Multiple Markers</h3><p>After getting one marker working, I wanted to place several.</p><p>Instead of storing a single point, I needed an array.</p><p>So I changed:</p><pre>const [marker, setMarker] = useState&lt;Point | null&gt;(null);</pre><p>to:</p><pre>const [markers, setMarkers] = useState&lt;Point[]&gt;([]);</pre><p>Point[] means an array containing multiple points.</p><p>The empty array means we start with no markers.</p><p>Now, whenever I click, I can add a new point:</p><pre>setMarkers((previous) =&gt; [<br>  ...previous,<br>  [point.x, point.y, point.z],<br>]);</pre><p>Let’s understand this carefully.</p><p>previous contains the markers already stored.</p><p>...previous copies those existing markers into the new array.</p><p>And the final array adds the new point.</p><p>So if I click three times, I might have:</p><pre>[<br>  [0.5, 0.3, 1],<br>  [-0.4, 0.7, 1],<br>  [1, -0.2, 0.6],<br>]</pre><p>Each entry represents a different marker.</p><p>To display them, I can use map():</p><pre>{markers.map((position, index) =&gt; (<br>  &lt;mesh key={index} position={position}&gt;<br>    &lt;sphereGeometry args={[0.08, 16, 16]} /&gt;<br>    &lt;meshBasicMaterial color=&quot;red&quot; /&gt;<br>  &lt;/mesh&gt;<br>))}</pre><p>map() goes through the array and creates one sphere for each point.</p><p>I used the array index as the key because this is a simple append-only example.</p><p>For an application where markers can be deleted or reordered, stable marker IDs would be a better choice.</p><h3>6. The Problem with World and Local Coordinates</h3><p>This was the most important part of today’s lesson.</p><p>I learned that event.point gives us a world-space position.</p><p>But when we place an object inside a group, its position is usually interpreted relative to that group.</p><p>Let’s imagine this:</p><pre>&lt;group position={[5, 0, 0]}&gt;<br>  &lt;mesh&gt;<br>    &lt;boxGeometry args={[2, 2, 2]} /&gt;<br>    &lt;meshStandardMaterial color=&quot;orange&quot; /&gt;<br>  &lt;/mesh&gt;<br>&lt;/group&gt;</pre><p>The group is positioned 5 units along X.</p><p>The box is inside the group.</p><p>So even though the box’s local position is [0, 0, 0], its world position is [5, 0, 0].</p><p>Now suppose I click the center of the box.</p><p>The click might produce a world-space X coordinate around 5.</p><p>If I use that value directly as the local position of a marker inside the group, the marker will be offset incorrectly.</p><p>Why?</p><p>Because the group already contributes 5 units of translation.</p><p>The marker would receive that translation again.</p><p>So I need a way to convert the world-space point into the group’s local coordinate system.</p><p>That’s where worldToLocal() comes in.</p><h3>7. Understanding worldToLocal()</h3><p>Three.js provides a method called worldToLocal().</p><p>It converts a position from world coordinates into an object’s local coordinate system.</p><p>For example:</p><pre>const localPoint = group.worldToLocal(<br>  event.point.clone()<br>);</pre><p>Let’s break that down.</p><p>event.point is the world-space intersection point.</p><p>.clone() creates a separate copy of the Vector3.</p><p>We clone it because worldToLocal() modifies the vector passed to it.</p><p>And group.worldToLocal() converts the copied point into the group&#39;s local coordinates.</p><p>For example, if the group is translated by 5 units along X, a world-space point at X = 5 becomes local X = 0.</p><p>The method also accounts for rotations and scaling in the parent hierarchy.</p><p>This is why coordinate conversion is so important when working with nested 3D objects.</p><h3>8. My Complete Example with Local Coordinates</h3><p>Now let’s create a group containing a box and its markers.</p><p>We’ll position the group away from the origin.</p><p>Then we’ll convert each clicked point into the group’s local coordinates before storing it.</p><pre>&quot;use client&quot;;</pre><pre>import { useRef, useState } from &quot;react&quot;;<br>import { Canvas, type ThreeEvent } from &quot;@react-three/fiber&quot;;<br>import { OrbitControls } from &quot;@react-three/drei&quot;;<br>import { Group } from &quot;three&quot;;</pre><pre>type Point = [number, number, number];</pre><pre>function MarkableBox() {<br>  const groupRef = useRef&lt;Group&gt;(null);<br>  const [markers, setMarkers] = useState&lt;Point[]&gt;([]);</pre><pre>  function handleClick(event: ThreeEvent&lt;MouseEvent&gt;) {<br>    event.stopPropagation();</pre><pre>    const group = groupRef.current;<br>    if (!group) return;</pre><pre>    group.updateWorldMatrix(true, false);</pre><pre>    const localPoint = group.worldToLocal(<br>      event.point.clone()<br>    );</pre><pre>    setMarkers((previous) =&gt; [<br>      ...previous,<br>      [localPoint.x, localPoint.y, localPoint.z],<br>    ]);<br>  }</pre><pre>  return (<br>    &lt;group ref={groupRef} position={[2, 0, 0]}&gt;<br>      &lt;mesh onClick={handleClick}&gt;<br>        &lt;boxGeometry args={[2, 2, 2]} /&gt;<br>        &lt;meshStandardMaterial color=&quot;orange&quot; /&gt;<br>      &lt;/mesh&gt;</pre><pre>      {markers.map((position, index) =&gt; (<br>        &lt;mesh key={index} position={position}&gt;<br>          &lt;sphereGeometry args={[0.08, 16, 16]} /&gt;<br>          &lt;meshBasicMaterial color=&quot;red&quot; /&gt;<br>        &lt;/mesh&gt;<br>      ))}<br>    &lt;/group&gt;<br>  );<br>}</pre><pre>export default function Scene() {<br>  return (<br>    &lt;div style={{ height: 450 }}&gt;<br>      &lt;Canvas camera={{ position: [4, 3, 7] }}&gt;<br>        &lt;ambientLight intensity={0.5} /&gt;<br>        &lt;directionalLight position={[3, 5, 2]} intensity={2} /&gt;</pre><pre>        &lt;MarkableBox /&gt;</pre><pre>        &lt;OrbitControls /&gt;<br>      &lt;/Canvas&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>Let’s understand the most important lines.</p><p>First:</p><pre>const groupRef = useRef&lt;Group&gt;(null);</pre><p>This creates a reference to the Three.js group.</p><p>Next:</p><pre>&lt;group ref={groupRef} position={[2, 0, 0]}&gt;</pre><p>moves the group 2 units along X.</p><p>The box and markers are both children of that group.</p><p>Then:</p><pre>group.updateWorldMatrix(true, false);</pre><p>ensures that the group’s world transformation matrix is up to date.</p><p>After that:</p><pre>const localPoint = group.worldToLocal(<br>  event.point.clone()<br>);</pre><p>converts the world-space intersection point into the group’s local coordinates.</p><p>Finally:</p><pre>setMarkers((previous) =&gt; [<br>  ...previous,<br>  [localPoint.x, localPoint.y, localPoint.z],<br>]);</pre><p>stores the converted position.</p><p>Since the markers and box share the same parent group, they follow the group’s transformations together.</p><p>If I move or rotate the group, the markers move with the box.</p><p>That’s exactly what I wanted.</p><h3>9. One Small Problem: Markers Can Be Half-Buried</h3><p>There’s something else I noticed.</p><p>When I place a sphere exactly at the intersection point, its center sits on the surface.</p><p>That means part of the sphere may be inside the box.</p><p>For today’s lesson, that’s fine.</p><p>But in a polished 3D application, I might want the marker to sit slightly above the surface.</p><p>To do that, I would need to understand the surface’s normal direction.</p><p>That’s another concept worth exploring later.</p><p>For now, I’m focusing on correctly placing markers and understanding coordinate systems.</p><h3>10. Why This Matters in Real Applications</h3><p>This is one of the most useful things I’ve learned so far.</p><p>Raycasting allows users to interact with 3D models.</p><p>And marker placement gives us a way to identify particular locations on their surfaces.</p><p>Imagine a 3D measurement application.</p><p>A user clicks a model to place an anatomical landmark.</p><p>The application records the selected position.</p><p>Later, that position might be used as part of a measurement.</p><p>Of course, reliable measurements require more than simply recording a point.</p><p>We also need to handle coordinate systems, model units, geometry changes, and data persistence.</p><p>But today, I’ve learned an important building block.</p><p>I can click a 3D surface, obtain the intersection point, and place a marker there.</p><h3>What I Learned on Day 15</h3><p>Today, I learned that:</p><ul><li>event.point gives us the world-space intersection point.</li><li>A Vector3 contains X, Y, and Z coordinates.</li><li>We can use a small sphere as a 3D marker.</li><li>useState can store one marker or multiple markers.</li><li>map() can render a marker for every stored point.</li><li>Child objects use positions relative to their parent.</li><li>worldToLocal() converts world-space points into local coordinates.</li><li>.clone() prevents unwanted modification of the original vector.</li><li>Markers placed inside the same group as a model can follow its transformations.</li></ul><p>But my biggest takeaway is this:</p><p><strong>Knowing where a user clicked is only half the problem. We also need to understand which coordinate system that position belongs to.</strong></p><p>And now I understand why local and world coordinates matter so much in interactive 3D applications.</p><h3>What’s Next?</h3><p>For Day 16, I want to explore <strong>surface normals in Three.js</strong>.</p><p>Now that I can place markers on a surface, I want to understand how to position them slightly above that surface instead of leaving them half-buried inside the model.</p><p>I’ll also explore how normals describe which direction a surface is facing.</p><p>One concept at a time.</p><h3>References</h3><ul><li><a href="https://threejs.org/docs/#api/en/core/Raycaster">Three.js Raycaster Documentation</a></li><li><a href="https://threejs.org/docs/#api/en/core/Object3D">Three.js Object3D Documentation</a></li><li><a href="https://threejs.org/docs/#api/en/math/Vector3">Three.js Vector3 Documentation</a></li><li><a href="https://r3f.docs.pmnd.rs/api/events">React Three Fiber Events Documentation</a></li></ul><p><em>Day 15 of my Three.js learning journey — learning in public, one concept at a time.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0d6405292345" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 14 of Learning Three.js: Making 3D Objects Clickable with Raycasting and React Three Fiber]]></title>
            <link>https://medium.com/@chiomsyndev/day-14-of-learning-three-js-making-3d-objects-clickable-with-raycasting-and-react-three-fiber-24822f0dc2de?source=rss-39943d331ca7------2</link>
            <guid isPermaLink="false">https://medium.com/p/24822f0dc2de</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react-three-fiber]]></category>
            <category><![CDATA[threejs]]></category>
            <category><![CDATA[3d-graphics]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Mirian Ezeamama]]></dc:creator>
            <pubDate>Fri, 30 Oct 2026 15:44:22 GMT</pubDate>
            <atom:updated>2026-10-30T15:44:22.652Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UXHOeKNs5e-2eVEBPI5umg.png" /></figure><p><em>How I learned to click, select, and highlight 3D objects — and finally understood how Three.js knows what I clicked.</em></p><p>On Day 13 of my Three.js learning journey, I explored different types of lights.</p><p>I learned how ambient, directional, point, and spotlights behave differently.</p><p>But today, I wanted to do something completely different.</p><p>So far, I’ve been creating 3D objects, moving them, rotating them, scaling them, and changing their appearance.</p><p>But what if I want to interact with them?</p><p><strong>What if I want to click a 3D box and change its color?</strong></p><p>Or click a particular part of a model and place a marker there?</p><p>That led me to something called raycasting.</p><p>At first, the name sounded complicated.</p><p>But once I understood the basic idea, it started making sense.</p><p>Let’s explore it step by step.</p><h3>1. How Does Clicking a 3D Object Work?</h3><p>In a normal React application, we can create a button.</p><pre>&lt;button onClick={() =&gt; alert(&quot;Hello!&quot;)}&gt;<br>  Click me<br>&lt;/button&gt;</pre><p>When the user clicks the button, React runs the function.</p><p>That’s straightforward because a button is a regular HTML element.</p><p>But a Three.js box is different.</p><p>It’s a 3D object rendered inside a Canvas.</p><p>So how does React Three Fiber know which object I clicked?</p><p>The answer is raycasting.</p><h3>2. What Is Raycasting?</h3><p>Imagine pointing a laser pointer at a wall.</p><p>The laser begins at one position, travels in a direction, and hits the wall.</p><p>Raycasting works in a similar way.</p><p>A ray has two important properties.</p><p>An origin, which is where it begins.</p><p>And a direction, which tells us where it travels.</p><p>When we click inside a Three.js scene, React Three Fiber can create a ray using the camera and the pointer’s screen position.</p><p>It then checks whether the ray intersects any objects.</p><p>If the ray hits a box, React Three Fiber can trigger the box’s click handler.</p><p>The interesting part is that React Three Fiber already handles this for us.</p><p>We don’t need to create a raycaster manually just to make a box clickable.</p><h3>3. My First Clickable Box</h3><p>Let’s begin with a simple example.</p><pre>&quot;use client&quot;;</pre><pre>import { Canvas } from &quot;@react-three/fiber&quot;;</pre><pre>function ClickableBox() {<br>  return (<br>    &lt;mesh onClick={() =&gt; console.log(&quot;Box clicked!&quot;)}&gt;<br>      &lt;boxGeometry args={[1, 1, 1]} /&gt;<br>      &lt;meshBasicMaterial color=&quot;orange&quot; /&gt;<br>    &lt;/mesh&gt;<br>  );<br>}</pre><pre>export default function Scene() {<br>  return (<br>    &lt;div style={{ height: 400 }}&gt;<br>      &lt;Canvas camera={{ position: [3, 2, 5] }}&gt;<br>        &lt;ClickableBox /&gt;<br>      &lt;/Canvas&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>The new part is:</p><pre>onClick={() =&gt; console.log(&quot;Box clicked!&quot;)}</pre><p>Let’s break it down.</p><p>onClick is the event handler.</p><p>() =&gt; creates a function that runs when the event occurs.</p><p>And console.log() prints a message in the browser console.</p><p>So when I click the box, I see:</p><pre>Box clicked!</pre><p>That’s my first interaction with a 3D object!</p><p>But printing a message isn’t very exciting.</p><p>Let’s make the box change color.</p><h3>4. Changing the Box Color with useState</h3><p>To change the box’s appearance when clicked, we need React to remember whether the box is selected.</p><p>That’s where useState comes in.</p><pre>&quot;use client&quot;;</pre><pre>import { useState } from &quot;react&quot;;<br>import { Canvas } from &quot;@react-three/fiber&quot;;</pre><pre>function ClickableBox() {<br>  const [isSelected, setIsSelected] = useState(false);</pre><pre>  return (<br>    &lt;mesh onClick={() =&gt; setIsSelected(!isSelected)}&gt;<br>      &lt;boxGeometry args={[1, 1, 1]} /&gt;</pre><pre>      &lt;meshBasicMaterial<br>        color={isSelected ? &quot;green&quot; : &quot;orange&quot;}<br>      /&gt;<br>    &lt;/mesh&gt;<br>  );<br>}</pre><pre>export default function Scene() {<br>  return (<br>    &lt;div style={{ height: 400 }}&gt;<br>      &lt;Canvas camera={{ position: [3, 2, 5] }}&gt;<br>        &lt;ClickableBox /&gt;<br>      &lt;/Canvas&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>Let’s understand what changed.</p><p>First:</p><pre>const [isSelected, setIsSelected] = useState(false);</pre><p>This creates a state variable.</p><p>isSelected stores whether the box is selected.</p><p>setIsSelected lets us change that value.</p><p>And false means the box starts unselected.</p><p>Next:</p><pre>onClick={() =&gt; setIsSelected(!isSelected)}</pre><p>This changes the state whenever we click.</p><p>The ! symbol means &quot;not.&quot;</p><p>So if isSelected is false, clicking makes it true.</p><p>If it’s true, clicking makes it false.</p><p>Finally:</p><pre>color={isSelected ? &quot;green&quot; : &quot;orange&quot;}</pre><p>This uses a ternary expression.</p><p>If the box is selected, it becomes green.</p><p>Otherwise, it stays orange.</p><p>And just like that, we have a clickable 3D box!</p><h3>5. What Happens When We Have Multiple Boxes?</h3><p>Now imagine creating three boxes.</p><p>I want to click each box independently.</p><p>One simple way to achieve that is to give each box its own React state.</p><p>Let’s make our component reusable.</p><pre>function ClickableBox({ position }: { position: [number, number, number] }) {<br>  const [isSelected, setIsSelected] = useState(false);</pre><pre>  return (<br>    &lt;mesh<br>      position={position}<br>      onClick={() =&gt; setIsSelected(!isSelected)}<br>    &gt;<br>      &lt;boxGeometry args={[1, 1, 1]} /&gt;</pre><pre>      &lt;meshBasicMaterial<br>        color={isSelected ? &quot;green&quot; : &quot;orange&quot;}<br>      /&gt;<br>    &lt;/mesh&gt;<br>  );<br>}</pre><p>Now we can create multiple boxes:</p><pre>&lt;ClickableBox position={[-2, 0, 0]} /&gt;<br>&lt;ClickableBox position={[0, 0, 0]} /&gt;<br>&lt;ClickableBox position={[2, 0, 0]} /&gt;</pre><p>Each component instance has its own state.</p><p>So clicking one box doesn’t automatically change the others.</p><p>This is useful for creating interactive 3D scenes where users can select individual objects.</p><h3>6. What Happens Behind the Scenes?</h3><p>Although we’ve been using onClick, I wanted to understand what React Three Fiber is actually doing.</p><p>When we click inside the Canvas, React Three Fiber calculates a ray using the camera and the pointer position.</p><p>The ray travels through the 3D scene.</p><p>It checks which objects intersect the ray.</p><p>If a mesh is hit, React Three Fiber can trigger its pointer event handler.</p><p>This process is called raycasting.</p><p>The important thing is that we don’t need to manually calculate the ray for ordinary mesh click events.</p><p>React Three Fiber handles that work.</p><h3>7. Finding the Exact Point We Clicked</h3><p>Here’s something I found particularly interesting.</p><p>A click event doesn’t only tell us which object was clicked.</p><p>It can also tell us where the ray intersected the object.</p><p>For example:</p><pre>&lt;mesh<br>  onClick={(event) =&gt; {<br>    console.log(event.point);<br>  }}<br>&gt;</pre><p>The important part is:</p><pre>event.point</pre><p>This contains the intersection point in world coordinates.</p><p>It might contain values such as:</p><pre>Vector3 {<br>  x: 0.4,<br>  y: 0.2,<br>  z: 0.5<br>}</pre><p>The actual values depend on where we clicked.</p><p>This is useful when we want to place a marker on a 3D model.</p><p>For example, a user could click a surface, and the application could use the intersection point to position a marker.</p><p>That makes raycasting useful for interactive model viewers and measurement tools.</p><h3>8. Highlighting a Box When the Mouse Moves Over It</h3><p>Next, I wanted to make the box respond before clicking.</p><p>For example, what if the box turns yellow when I move my mouse over it?</p><p>React Three Fiber provides pointer events for this.</p><p>Two useful events are:</p><p>onPointerOver, which runs when the pointer enters an object&#39;s hit area.</p><p>And onPointerOut, which runs when the pointer leaves it.</p><p>Here’s an example:</p><pre>&quot;use client&quot;;</pre><pre>import { useState } from &quot;react&quot;;<br>import { Canvas } from &quot;@react-three/fiber&quot;;</pre><pre>function HoverBox() {<br>  const [hovered, setHovered] = useState(false);</pre><pre>  return (<br>    &lt;mesh<br>      onPointerOver={() =&gt; setHovered(true)}<br>      onPointerOut={() =&gt; setHovered(false)}<br>    &gt;<br>      &lt;boxGeometry args={[1, 1, 1]} /&gt;</pre><pre>      &lt;meshBasicMaterial<br>        color={hovered ? &quot;yellow&quot; : &quot;orange&quot;}<br>      /&gt;<br>    &lt;/mesh&gt;<br>  );<br>}</pre><pre>export default function Scene() {<br>  return (<br>    &lt;div style={{ height: 400 }}&gt;<br>      &lt;Canvas camera={{ position: [3, 2, 5] }}&gt;<br>        &lt;HoverBox /&gt;<br>      &lt;/Canvas&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>When the pointer enters the box, hovered becomes true.</p><p>When the pointer leaves, it becomes false.</p><p>The material changes color based on that value.</p><p>This makes the scene feel more interactive.</p><h3>9. Combining Click and Hover Interactions</h3><p>Now let’s create a slightly more complete example.</p><p>We’ll have three boxes.</p><p>Each box can be hovered and clicked independently.</p><pre>&quot;use client&quot;;</pre><pre>import { useState } from &quot;react&quot;;<br>import { Canvas } from &quot;@react-three/fiber&quot;;<br>import { OrbitControls } from &quot;@react-three/drei&quot;;</pre><pre>type BoxProps = {<br>  position: [number, number, number];<br>};</pre><pre>function ClickableBox({ position }: BoxProps) {<br>  const [selected, setSelected] = useState(false);<br>  const [hovered, setHovered] = useState(false);</pre><pre>  return (<br>    &lt;mesh<br>      position={position}<br>      onClick={(event) =&gt; {<br>        event.stopPropagation();<br>        setSelected((previous) =&gt; !previous);<br>      }}<br>      onPointerOver={(event) =&gt; {<br>        event.stopPropagation();<br>        setHovered(true);<br>      }}<br>      onPointerOut={() =&gt; setHovered(false)}<br>    &gt;<br>      &lt;boxGeometry args={[1, 1, 1]} /&gt;</pre><pre>      &lt;meshStandardMaterial<br>        color={<br>          selected<br>            ? &quot;green&quot;<br>            : hovered<br>              ? &quot;yellow&quot;<br>              : &quot;orange&quot;<br>        }<br>      /&gt;<br>    &lt;/mesh&gt;<br>  );<br>}</pre><pre>export default function Scene() {<br>  return (<br>    &lt;div style={{ height: 450 }}&gt;<br>      &lt;Canvas camera={{ position: [4, 3, 7] }}&gt;<br>        &lt;ambientLight intensity={0.5} /&gt;</pre><pre>        &lt;directionalLight<br>          position={[3, 5, 2]}<br>          intensity={2}<br>        /&gt;</pre><pre>        &lt;ClickableBox position={[-2, 0, 0]} /&gt;<br>        &lt;ClickableBox position={[0, 0, 0]} /&gt;<br>        &lt;ClickableBox position={[2, 0, 0]} /&gt;</pre><pre>        &lt;OrbitControls /&gt;<br>      &lt;/Canvas&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>This example introduces a few important ideas.</p><p>First, we have two state variables.</p><p>One tracks selection.</p><p>The other tracks hover.</p><p>Next, we use:</p><pre>setSelected((previous) =&gt; !previous);</pre><p>This toggles the selected state based on its previous value.</p><p>Then we use:</p><pre>event.stopPropagation();</pre><p>This stops the pointer event from continuing to other intersections and along its normal propagation path.</p><p>That can help prevent a click on the front box from also selecting a box behind it.</p><p>Finally, we use a conditional color expression.</p><p>Green means selected.</p><p>Yellow means hovered but not selected.</p><p>Orange means neither selected nor hovered.</p><p>This is a simple but useful interaction pattern.</p><h3>10. Why Raycasting Matters in Real Applications</h3><p>At first, raycasting sounded like a complicated mathematical topic.</p><p>But now I understand why it’s important.</p><p>Raycasting helps us identify objects and points in a 3D scene.</p><p>It’s useful for selecting models, placing markers, highlighting surfaces, and building interactive tools.</p><p>For example, imagine clicking a 3D model and placing a measurement landmark at the clicked position.</p><p>The raycast intersection can provide the world-space coordinates of that point.</p><p>Of course, accurate measurement applications need additional handling for coordinate systems, model units, and geometry.</p><p>But raycasting provides an important starting point.</p><p>And that’s why I wanted to understand it before moving on to more advanced 3D interactions.</p><h3>What I Learned on Day 14</h3><p>Today, I learned that:</p><ul><li>Raycasting helps identify objects under the mouse pointer.</li><li>React Three Fiber performs raycasting for its pointer events.</li><li>onClick lets us respond to clicks on 3D objects.</li><li>useState can track whether an object is selected.</li><li>onPointerOver and onPointerOut let us create hover effects.</li><li>event.point provides the world-space intersection point.</li><li>event.stopPropagation() can prevent events from reaching other intersections.</li><li>Each component instance can manage its own interaction state.</li></ul><p>But my biggest takeaway is this:</p><p><strong>A 3D object doesn’t have to be something we only look at. It can respond to our actions.</strong></p><p>And that opens the door to much more interesting applications.</p><h3>What’s Next?</h3><p>For Day 15, I want to explore <strong>placing markers on 3D surfaces using raycasting</strong>.</p><p>Now that I know how to detect a click and obtain its intersection point, I want to learn how to place a small sphere exactly where I clicked.</p><p>I’ll also explore why local and world coordinates matter when placing markers on objects inside groups.</p><p>One concept at a time. 😄</p><h3>References</h3><ul><li><a href="https://threejs.org/docs/#api/en/core/Raycaster">Three.js Raycaster Documentation</a></li><li><a href="https://threejs.org/docs/#api/en/math/Vector3">Three.js Vector3 Documentation</a></li><li><a href="https://r3f.docs.pmnd.rs/api/events">React Three Fiber Events Documentation</a></li><li><a href="https://r3f.docs.pmnd.rs/">React Three Fiber Documentation</a></li></ul><p><em>Day 14 of my Three.js learning journey — learning in public, one concept at a time.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24822f0dc2de" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 13 of Learning Three.js: Understanding Different Types of Lights in React Three Fiber]]></title>
            <link>https://medium.com/@chiomsyndev/day-13-of-learning-three-js-understanding-different-types-of-lights-in-react-three-fiber-9c5a4e406d05?source=rss-39943d331ca7------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c5a4e406d05</guid>
            <category><![CDATA[react-three-fiber]]></category>
            <category><![CDATA[3d-graphics]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[threejs]]></category>
            <dc:creator><![CDATA[Mirian Ezeamama]]></dc:creator>
            <pubDate>Thu, 29 Oct 2026 14:46:21 GMT</pubDate>
            <atom:updated>2026-10-29T14:46:21.519Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UXHOeKNs5e-2eVEBPI5umg.png" /></figure><p><em>From sunlight to light bulbs and flashlights — learning how ambient, directional, point, and spot lights work in Three.js.</em></p><p>On Day 11 of my Three.js learning journey, I learned how materials respond to lighting.</p><p>On Day 12, I finally made my orange box cast a shadow onto the floor.</p><p>But something caught my attention.</p><p>So far, I’ve mostly been using two lights:</p><pre>&lt;ambientLight intensity={0.4} /&gt;<br>&lt;directionalLight position={[3, 5, 2]} intensity={2} /&gt;</pre><p>And I started wondering:</p><p><strong>Why does Three.js have different types of lights? Why can’t I just use one light for everything?</strong></p><p>Today, I decided to explore four important light types: ambient, directional, point, and spot lights.</p><p>I’m keeping things simple because I want to understand how each one behaves before combining them into complicated scenes.</p><h3>1. Why Do We Need Different Types of Lights?</h3><p>Think about the lights we encounter in everyday life.</p><p>The Sun illuminates outdoor spaces.</p><p>A light bulb illuminates the area around it.</p><p>A flashlight sends light primarily in one direction.</p><p>These lights behave differently.</p><p>And that’s why Three.js provides different light types.</p><p>We can choose a light depending on the effect we want to create.</p><p>Today, I’m focusing on four types.</p><ul><li>Ambient light</li><li>Directional light</li><li>Point light</li><li>Spotlight</li></ul><p>Let’s understand them one at a time.</p><h3>2. Ambient Light: General Illumination</h3><p>We’ve already used ambient light in our earlier lessons.</p><p>Here’s an example:</p><pre>&lt;ambientLight intensity={0.5} /&gt;</pre><p>Ambient light illuminates objects uniformly.</p><p>It doesn’t have a particular direction.</p><p>And it doesn’t cast shadows.</p><p>This makes it useful when I want to add general illumination to a scene.</p><p>But there’s something important to remember.</p><p>Ambient light alone doesn’t create directional shading.</p><p>That means it won’t make one side of a box brighter just because that side faces a particular direction.</p><p>For that, we need a different kind of light.</p><h3>3. Directional Light: Like Sunlight</h3><p>The next light is directionalLight.</p><p>We’ve also used this before.</p><pre>&lt;directionalLight<br>  position={[3, 5, 2]}<br>  intensity={2}<br>/&gt;</pre><p>A directional light sends parallel light rays through the scene.</p><p>I like to think of it as sunlight.</p><p>The Sun is so far away that its rays are approximately parallel over the small areas we’re usually modelling.</p><p>One thing I learned is that a directional light’s position helps determine its direction.</p><p>By default, the light points toward the origin.</p><p>So the light’s position and target determine which direction it shines.</p><p>Unlike a point light, a directional light doesn’t get weaker simply because an object is farther away.</p><p>That’s useful for simulating sunlight across a scene.</p><h3>4. Point Light: Like a Light Bulb</h3><p>Now we reach something new.</p><p>A point light.</p><p>Imagine placing a glowing bulb in the middle of a dark room.</p><p>The bulb emits light outward in many directions.</p><p>Objects closer to the bulb receive stronger illumination.</p><p>Objects farther away generally receive less.</p><p>That’s how a point light behaves.</p><p>Here’s the code:</p><pre>&lt;pointLight<br>  position={[0, 3, 0]}<br>  intensity={30}<br>/&gt;</pre><p>Let’s break it down.</p><p>pointLight creates a light that radiates outward from a position.</p><p>position={[0, 3, 0]} places the light 3 units above the origin.</p><p>And intensity={30} controls how much light it emits.</p><p>The intensity value is simply a starting point for experimentation.</p><p>The actual brightness depends on the scene, the distance to objects, and the rendering settings.</p><p>One interesting difference between a point light and a directional light is distance attenuation.</p><p>A point light normally becomes weaker as distance increases.</p><p>A directional light doesn’t behave that way.</p><p>That makes sense when I think about a light bulb versus sunlight.</p><h3>5. Spotlight: Like a Flashlight</h3><p>The next light is a spotlight.</p><p>Imagine holding a flashlight.</p><p>It doesn’t illuminate everything around you equally.</p><p>Instead, it sends light into a cone.</p><p>That’s similar to a spotlight in Three.js.</p><p>Here’s an example:</p><pre>&lt;spotLight<br>  position={[0, 5, 0]}<br>  intensity={50}<br>  angle={Math.PI / 6}<br>  penumbra={0.5}<br>/&gt;</pre><p>At first, this looked more complicated than the other lights.</p><p>But let’s break it down.</p><p>spotLight creates the spotlight.</p><p>position tells Three.js where the light is located.</p><p>intensity controls its strength.</p><p>angle controls how wide the light cone is.</p><p>And penumbra controls how softly the illumination fades near the cone&#39;s edges.</p><h3>Understanding the Angle</h3><p>Remember from Day 7 that Three.js uses radians for angles.</p><p>For example:</p><pre>angle={Math.PI / 6}</pre><p>means 30 degrees.</p><p>This is the half-angle of the spotlight cone.</p><p>So the complete cone spans approximately 60 degrees.</p><p>If I increase the angle, the spotlight illuminates a wider area.</p><p>If I decrease it, the light becomes more focused.</p><p>That’s similar to adjusting a flashlight’s beam.</p><h3>Understanding Penumbra</h3><p>This was another new word for me.</p><p>Penumbra describes the softness of the transition near the spotlight cone’s edges.</p><p>For example:</p><pre>penumbra={0}</pre><p>creates a sharper transition.</p><p>While:</p><pre>penumbra={1}</pre><p>creates a softer transition across more of the cone.</p><p>One important distinction is that penumbra doesn’t directly control how soft cast shadow edges are.</p><p>It controls the light cone’s falloff.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mSOxABbsCrmLei2XV6P6Xg.png" /></figure><h3>6. Comparing the Four Lights</h3><p>Here’s the simple comparison I made.</p><p>LightHow It WorksReal-Life ExampleAmbientUniform illuminationGeneral background lightingDirectionalParallel rays from one directionSunlightPointLight radiates from a positionLight bulbSpotLight shines within a coneFlashlight</p><p>The easiest way for me to remember them is:</p><p><strong>Ambient fills. Directional shines. Point radiates. Spot focuses.</strong></p><h3>7. My First Scene Using a Point Light</h3><p>Now let’s create a simple React Three Fiber scene.</p><p>I’ll use a box with a standard material and illuminate it with a point light.</p><pre>&quot;use client&quot;;</pre><pre>import { Canvas } from &quot;@react-three/fiber&quot;;<br>import { OrbitControls } from &quot;@react-three/drei&quot;;</pre><pre>function MyScene() {<br>  return (<br>    &lt;&gt;<br>      &lt;ambientLight intensity={0.2} /&gt;</pre><pre>      &lt;pointLight<br>        position={[2, 3, 2]}<br>        intensity={50}<br>      /&gt;</pre><pre>      &lt;mesh&gt;<br>        &lt;boxGeometry args={[2, 2, 2]} /&gt;<br>        &lt;meshStandardMaterial color=&quot;orange&quot; /&gt;<br>      &lt;/mesh&gt;</pre><pre>      &lt;OrbitControls /&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><pre>export default function Scene() {<br>  return (<br>    &lt;div style={{ height: 400 }}&gt;<br>      &lt;Canvas camera={{ position: [4, 3, 6] }}&gt;<br>        &lt;MyScene /&gt;<br>      &lt;/Canvas&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>Let’s understand the important parts.</p><p>First:</p><pre>&lt;ambientLight intensity={0.2} /&gt;</pre><p>This provides a small amount of general illumination.</p><p>Next:</p><pre>&lt;pointLight<br>  position={[2, 3, 2]}<br>  intensity={50}<br>/&gt;</pre><p>This places a point light above and to the side of the box.</p><p>The light radiates outward from that position.</p><p>Then:</p><pre>&lt;meshStandardMaterial color=&quot;orange&quot; /&gt;</pre><p>gives our box a material that responds to the light.</p><p>And finally:</p><pre>&lt;OrbitControls /&gt;</pre><p>lets us inspect the scene from different angles.</p><p>Now I can experiment by moving the light.</p><p>For example, changing the position from:</p><pre>position={[2, 3, 2]}</pre><p>to:</p><pre>position={[-2, 3, 2]}</pre><p>moves the light to the opposite side along X.</p><p>This changes which surfaces receive stronger illumination.</p><h3>8. Replacing the Point Light with a Spotlight</h3><p>Next, I wanted to compare a point light and a spotlight.</p><p>So I removed the point light:</p><pre>&lt;pointLight position={[2, 3, 2]} intensity={50} /&gt;</pre><p>And replaced it with:</p><pre>&lt;spotLight<br>  position={[0, 5, 0]}<br>  intensity={80}<br>  angle={Math.PI / 6}<br>  penumbra={0.5}<br>/&gt;</pre><p>Now the light shines within a cone.</p><p>By default, the spotlight points toward the origin.</p><p>Since my box is at the origin, it receives illumination from above.</p><p>The important difference is that the spotlight focuses its light within a cone, while the point light radiates in all directions.</p><h3>9. Can We Use Multiple Lights Together?</h3><p>Yes!</p><p>In fact, many 3D scenes use several lights.</p><p>For example:</p><pre>&lt;ambientLight intensity={0.2} /&gt;</pre><pre>&lt;directionalLight<br>  position={[3, 5, 2]}<br>  intensity={1.5}<br>/&gt;</pre><pre>&lt;pointLight<br>  position={[-3, 2, 1]}<br>  intensity={20}<br>/&gt;</pre><p>Here, the ambient light provides general illumination.</p><p>The directional light helps reveal the object’s shape.</p><p>And the point light illuminates from another position.</p><p>But I also learned that adding more lights doesn’t automatically make a scene better.</p><p>Lighting has a performance cost.</p><p>So it’s better to start simple and add lights only when needed.</p><h3>10. Why This Matters in Real 3D Applications</h3><p>Understanding lighting is useful in almost every 3D application.</p><p>In a game, point lights can represent lamps or glowing objects.</p><p>Spotlights can represent flashlights or stage lighting.</p><p>Directional lights can simulate sunlight.</p><p>And ambient light can help keep a scene from becoming completely dark.</p><p>In a 3D model viewer, lighting can also help users understand surface shape and orientation.</p><p>Now I understand why choosing the right light matters.</p><p>It’s not just about making an object brighter.</p><p>It’s about controlling how the scene is illuminated.</p><h3>What I Learned on Day 13</h3><p>Today, I learned that:</p><ul><li>Ambient light provides uniform illumination.</li><li>Directional light creates parallel light rays.</li><li>Point light radiates outward from a position.</li><li>Point light intensity normally decreases with distance.</li><li>Spotlight illumination is limited to a cone.</li><li>Spotlight angle controls the cone&#39;s width.</li><li>Spotlight penumbra controls the softness of the cone&#39;s edges.</li><li>Multiple lights can work together in one scene.</li></ul><p>But my biggest takeaway is this:</p><p><strong>Different lights exist because they produce different illumination patterns.</strong></p><p>And now, instead of adding lights randomly, I can start thinking about what kind of illumination I actually want.</p><h3>What’s Next?</h3><p>For Day 14, I want to explore <strong>3D object interaction using raycasting</strong>.</p><p>So far, I’ve been creating, moving, rotating, and lighting objects.</p><p>But what if I want to click a box and change its color?</p><p>How does Three.js know which object I clicked?</p><p>That’s what I want to understand next.</p><p>One concept at a time.</p><h3>References</h3><ul><li><a href="https://threejs.org/manual/#en/lights">Three.js Lights Documentation</a></li><li><a href="https://threejs.org/docs/#api/en/lights/PointLight">Three.js PointLight Documentation</a></li><li><a href="https://threejs.org/docs/#api/en/lights/SpotLight">Three.js SpotLight Documentation</a></li><li><a href="https://r3f.docs.pmnd.rs/">React Three Fiber Documentation</a></li></ul><p><em>Day 13 of my Three.js learning journey — learning in public, one concept at a time.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c5a4e406d05" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 12 of Learning Three.js: Understanding Shadows in React Three Fiber]]></title>
            <link>https://medium.com/@chiomsyndev/day-12-of-learning-three-js-understanding-shadows-in-react-three-fiber-89d316d06cb4?source=rss-39943d331ca7------2</link>
            <guid isPermaLink="false">https://medium.com/p/89d316d06cb4</guid>
            <category><![CDATA[3d-graphics]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[threejs]]></category>
            <category><![CDATA[react-three-fiber]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Mirian Ezeamama]]></dc:creator>
            <pubDate>Wed, 28 Oct 2026 14:47:43 GMT</pubDate>
            <atom:updated>2026-10-28T14:47:43.450Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UXHOeKNs5e-2eVEBPI5umg.png" /></figure><p><em>How I made my first 3D box cast a shadow and why enabling shadows takes more than adding a light.</em></p><p>On Day 11 of my Three.js learning journey, I explored lights and materials.</p><p>I learned how meshBasicMaterial differs from meshStandardMaterial, and how ambientLight and directionalLight can change the appearance of a 3D object.</p><p>My orange box finally looked more three-dimensional.</p><p>But there was still something missing.</p><p><strong>My box wasn’t casting a visible shadow on the floor.</strong></p><p>That made me curious.</p><p>If I already have a light in my scene, shouldn’t shadows appear automatically?</p><p>Apparently not!</p><p>So for Day 12, I decided to understand how shadows work in Three.js.</p><p>I’ll start with a simple box, a light, and a floor.</p><p>Nothing complicated.</p><h3>1. What Is a Shadow?</h3><p>Imagine standing outside on a sunny afternoon.</p><p>Sunlight travels toward you.</p><p>Your body blocks some of that light.</p><p>And a darker region appears on the ground.</p><p>That’s a shadow.</p><p>The same basic idea applies in a 3D scene.</p><p>To create a visible shadow, we need three important things.</p><p>First, a light source.</p><p>Second, an object that blocks the light.</p><p>Third, a surface where the shadow can appear.</p><p>In our example, the directional light will illuminate the scene.</p><p>The box will block some of that light.</p><p>And the floor will display the shadow.</p><p>That sounds simple enough.</p><p>But Three.js needs us to configure these things.</p><h3>2. Why Don’t Shadows Appear Automatically?</h3><p>This was my first question.</p><p>Why doesn’t adding a light automatically create shadows?</p><p>The reason is that rendering shadows requires additional calculations.</p><p>Three.js needs to determine which parts of the scene are illuminated and which parts are blocked from the light.</p><p>One common technique is called shadow mapping.</p><p>The basic idea is that Three.js renders depth information from the light’s perspective and uses it to determine which surfaces should be in shadow.</p><p>Fortunately, we don’t have to implement those calculations ourselves.</p><p>React Three Fiber and Three.js handle the rendering.</p><p>We just need to enable the right settings.</p><h3>3. Step One: Enable Shadows on Canvas</h3><p>Let’s start with our Canvas.</p><p>Previously, we used:</p><pre>&lt;Canvas&gt;</pre><p>Now we’ll write:</p><pre>&lt;Canvas shadows&gt;</pre><p>The new property is shadows.</p><p>This tells React Three Fiber to enable shadow mapping.</p><p>But this alone isn’t enough.</p><p>We still need a light that produces shadows.</p><h3>4. Step Two: Enable Shadows on the Light</h3><p>On Day 11, we used a directional light.</p><p>Let’s use it again.</p><pre>&lt;directionalLight<br>  position={[3, 5, 2]}<br>  intensity={2}<br>  castShadow<br>/&gt;</pre><p>The new property is:</p><pre>castShadow</pre><p>This tells Three.js that the light should generate shadows.</p><p>The position determines the direction of the light.</p><p>And intensity controls its strength.</p><p>One important thing I learned is that not every light in a scene needs to cast shadows.</p><p>Shadow calculations have a performance cost.</p><p>So we should enable them where they’re actually needed.</p><h3>5. Step Three: Make the Box Cast a Shadow</h3><p>Now let’s create our box.</p><pre>&lt;mesh castShadow position={[0, 1, 0]}&gt;<br>  &lt;boxGeometry args={[1, 1, 1]} /&gt;<br>  &lt;meshStandardMaterial color=&quot;orange&quot; /&gt;<br>&lt;/mesh&gt;</pre><p>Let’s understand the important parts.</p><p>mesh creates our renderable object.</p><p>boxGeometry gives it a box shape.</p><p>meshStandardMaterial gives it a material that reacts to lighting.</p><p>But the important new property is:</p><pre>castShadow</pre><p>This tells Three.js that the box can cast shadows.</p><p>I also positioned the box at:</p><pre>position={[0, 1, 0]}</pre><p>That moves it 1 unit upward along the Y-axis.</p><p>Why?</p><p>Because I want the box to sit above the floor.</p><p>Since the box is 1 unit tall, its bottom is at Y = 0.5.</p><p>And our floor will be at Y = 0.</p><p>So there will be a small gap beneath the box.</p><h3>6. Step Four: Create a Floor That Receives Shadows</h3><p>Now we need somewhere for the shadow to appear.</p><p>Let’s create a floor.</p><pre>&lt;mesh rotation={[-Math.PI / 2, 0, 0]} receiveShadow&gt;<br>  &lt;planeGeometry args={[10, 10]} /&gt;<br>  &lt;meshStandardMaterial color=&quot;lightgray&quot; /&gt;<br>&lt;/mesh&gt;</pre><p>At first, this code confused me.</p><p>Especially this part:</p><pre>rotation={[-Math.PI / 2, 0, 0]}</pre><p>Why do we need to rotate the floor?</p><p>Because a plane in Three.js starts in the XY plane.</p><p>But we want our floor to lie horizontally in the XZ plane.</p><p>So we rotate it by −90 degrees around the X-axis.</p><p>Remember that Math.PI represents 180 degrees in radians.</p><p>So Math.PI / 2 represents 90 degrees.</p><p>The negative sign means we’re rotating in the opposite direction.</p><p>Next:</p><pre>&lt;planeGeometry args={[10, 10]} /&gt;</pre><p>creates a flat surface with dimensions of 10 by 10 units.</p><p>And:</p><pre>receiveShadow</pre><p>tells Three.js that the floor can display shadows cast onto it.</p><p>That was the missing piece.</p><h3>7. My First Complete Shadow Scene</h3><p>Now let’s put everything together.</p><pre>&quot;use client&quot;;</pre><pre>import { Canvas } from &quot;@react-three/fiber&quot;;<br>import { OrbitControls } from &quot;@react-three/drei&quot;;</pre><pre>function ShadowScene() {<br>  return (<br>    &lt;&gt;<br>      &lt;ambientLight intensity={0.4} /&gt;</pre><pre>      &lt;directionalLight<br>        position={[3, 5, 2]}<br>        intensity={2}<br>        castShadow<br>      /&gt;</pre><pre>      &lt;mesh castShadow position={[0, 1, 0]}&gt;<br>        &lt;boxGeometry args={[1, 1, 1]} /&gt;<br>        &lt;meshStandardMaterial color=&quot;orange&quot; /&gt;<br>      &lt;/mesh&gt;</pre><pre>      &lt;mesh<br>        rotation={[-Math.PI / 2, 0, 0]}<br>        receiveShadow<br>      &gt;<br>        &lt;planeGeometry args={[10, 10]} /&gt;<br>        &lt;meshStandardMaterial color=&quot;lightgray&quot; /&gt;<br>      &lt;/mesh&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><pre>export default function Scene() {<br>  return (<br>    &lt;div style={{ height: 450 }}&gt;<br>      &lt;Canvas<br>        shadows<br>        camera={{ position: [4, 3, 6] }}<br>      &gt;<br>        &lt;ShadowScene /&gt;<br>        &lt;OrbitControls /&gt;<br>      &lt;/Canvas&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>Now let’s review what makes the shadow work.</p><p>First:</p><pre>&lt;Canvas shadows&gt;</pre><p>enables shadow mapping.</p><p>Second:</p><pre>&lt;directionalLight castShadow /&gt;</pre><p>allows the light to generate shadows.</p><p>Third:</p><pre>&lt;mesh castShadow&gt;</pre><p>allows the box to cast a shadow.</p><p>And finally:</p><pre>&lt;mesh receiveShadow&gt;</pre><p>allows the floor to display the shadow.</p><p>All four settings work together.</p><p>If I forget to enable shadows on Canvas, the shadow won’t appear.</p><p>If I forget castShadow on the box, it won&#39;t cast a shadow.</p><p>And if I forget receiveShadow on the floor, the floor won&#39;t display the shadow.</p><p>That’s the main lesson.</p><h3>8. What Happens When I Move the Light?</h3><p>After getting the shadow to appear, I wanted to experiment.</p><p>What would happen if I moved the light?</p><p>For example, I could change:</p><pre>position={[3, 5, 2]}</pre><p>to:</p><pre>position={[-3, 5, 2]}</pre><p>Now the light comes from a different direction.</p><p>And the shadow moves accordingly.</p><p>This makes sense when I think about real life.</p><p>If the Sun moves across the sky, shadows change direction.</p><p>The same principle applies in our 3D scene.</p><p>One interesting thing I learned is that directional lights behave differently from point lights.</p><p>A directional light creates illumination from a particular direction, and its intensity doesn’t decrease simply because an object is farther away.</p><p>That’s why directional lights are commonly used to simulate sunlight.</p><h3>9. Why Do Some Shadows Look Pixelated?</h3><p>Another thing I discovered is that shadows don’t always look smooth.</p><p>Sometimes, their edges look jagged or pixelated.</p><p>Why?</p><p>Because shadow mapping uses a texture to store shadow information.</p><p>And that texture has a limited resolution.</p><p>We can adjust the shadow map resolution.</p><p>For example:</p><pre>&lt;directionalLight<br>  position={[3, 5, 2]}<br>  castShadow<br>  shadow-mapSize={[2048, 2048]}<br>/&gt;</pre><p>The new property is:</p><pre>shadow-mapSize={[2048, 2048]}</pre><p>This tells Three.js to use a shadow map that’s 2048 pixels wide and 2048 pixels tall.</p><p>A higher resolution can improve shadow detail.</p><p>But it also uses more GPU memory and rendering resources.</p><p>So increasing it isn’t always the best solution.</p><p>For now, I’m happy to start with the default settings.</p><h3>10. Why Shadows Matter in Real 3D Applications</h3><p>At first, I thought shadows were mainly for making 3D scenes look realistic.</p><p>But they’re useful for something else too.</p><p>They help us understand where objects are in relation to other surfaces.</p><p>Imagine a box floating above the floor.</p><p>Without a shadow, it might be difficult to judge its position.</p><p>With a shadow, we get an additional visual clue.</p><p>Shadows are useful in games, product visualization, architectural scenes, and interactive 3D environments.</p><p>But I also learned that shadows are only visual cues.</p><p>They shouldn’t replace actual geometry calculations when accurate measurements are needed.</p><h3>What I Learned on Day 12</h3><p>Today, I learned that:</p><ul><li>Shadows appear when objects block light.</li><li>Three.js needs additional configuration to render shadows.</li><li>&lt;Canvas shadows&gt; enables shadow mapping.</li><li>castShadow allows lights and objects to participate in shadow casting.</li><li>receiveShadow allows a surface to display shadows.</li><li>A plane can be rotated to act as a floor.</li><li>Moving the light changes the shadow’s direction.</li><li>Shadow map resolution affects shadow detail and performance.</li></ul><p>But my biggest takeaway is this:</p><p><strong>Adding a light isn’t enough to create a visible shadow. The light, the object, and the receiving surface must all be configured correctly.</strong></p><p>And now my orange box finally casts a shadow!</p><h3>What’s Next?</h3><p>For Day 13, I want to explore <strong>different types of lights in Three.js</strong>.</p><p>We’ve already used ambient and directional lights.</p><p>But I want to understand point lights, spotlights, and how light distance and direction affect a scene.</p><p>I’ll start with simple examples and gradually compare them.</p><p>One concept at a time.</p><h3>References</h3><ul><li><a href="https://threejs.org/manual/#en/shadows">Three.js Shadows Documentation</a></li><li><a href="https://threejs.org/docs/#api/en/lights/DirectionalLight">Three.js DirectionalLight Documentation</a></li><li><a href="https://threejs.org/docs/#api/en/geometries/PlaneGeometry">Three.js PlaneGeometry Documentation</a></li><li><a href="https://r3f.docs.pmnd.rs/">React Three Fiber Documentation</a></li></ul><p><em>Day 12 of my Three.js learning journey — learning in public, one concept at a time.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89d316d06cb4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 11 of Learning Three.js: Understanding Lights and Materials in React Three Fiber]]></title>
            <link>https://medium.com/@chiomsyndev/day-11-of-learning-three-js-understanding-lights-and-materials-in-react-three-fiber-425d5ac8dc8a?source=rss-39943d331ca7------2</link>
            <guid isPermaLink="false">https://medium.com/p/425d5ac8dc8a</guid>
            <category><![CDATA[react-three-fiber]]></category>
            <category><![CDATA[3d-graphics]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[threejs]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Mirian Ezeamama]]></dc:creator>
            <pubDate>Tue, 27 Oct 2026 14:56:07 GMT</pubDate>
            <atom:updated>2026-10-27T14:56:07.577Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4OwH0Y7DPnQ5MX-4kZje9w.png" /></figure><p><em>Why some 3D objects look flat, how light changes their appearance, and how I created my first shaded 3D box.</em></p><p>On Day 10 of my Three.js learning journey, I explored cameras.</p><p>I learned how camera position, field of view, and OrbitControls change how we see objects in a 3D scene.</p><p>But something had been bothering me since the beginning of this journey.</p><p>Almost every box I’ve created uses this material:</p><pre>&lt;meshBasicMaterial color=&quot;orange&quot; /&gt;</pre><p>And the box always appears orange, even when I haven’t added any lights.</p><p>That made me wonder:</p><p><strong>How can a 3D object be visible without light?</strong></p><p>And why do some 3D objects look flat while others look more realistic?</p><p>Today, I decided to understand how lights and materials work in Three.js.</p><p>I’m starting with a simple box because I want to understand the concepts before making things more complicated.</p><h3>1. What Is a Material?</h3><p>Imagine two boxes sitting on a table.</p><p>One is made of shiny metal.</p><p>The other is made of rough plastic.</p><p>Both boxes might have exactly the same shape and size.</p><p>But they look different because their surfaces interact with light differently.</p><p>In Three.js, a material controls how an object’s surface is rendered.</p><p>Let’s look at the box we’ve been creating.</p><pre>&lt;mesh&gt;<br>  &lt;boxGeometry args={[1, 1, 1]} /&gt;<br>  &lt;meshBasicMaterial color=&quot;orange&quot; /&gt;<br>&lt;/mesh&gt;</pre><p>The mesh represents the object.</p><p>The boxGeometry defines its shape.</p><p>And the meshBasicMaterial defines how its surface appears.</p><p>So I like to think of it this way:</p><p><strong>Geometry is the shape. Material is the appearance.</strong></p><p>That simple distinction helped me understand why we need both.</p><h3>2. Why Does meshBasicMaterial Work Without Lights?</h3><p>This was my first big question.</p><p>Why does a box with meshBasicMaterial remain visible even when I haven&#39;t added any lights?</p><p>The answer is that meshBasicMaterial doesn&#39;t respond to scene lighting.</p><p>It uses its material properties without calculating illumination from our lights.</p><p>For example:</p><pre>&lt;mesh&gt;<br>  &lt;boxGeometry args={[1, 1, 1]} /&gt;<br>  &lt;meshBasicMaterial color=&quot;orange&quot; /&gt;<br>&lt;/mesh&gt;</pre><p>This box can appear orange even without an ambient light or directional light.</p><p>That’s useful for simple examples, debugging, and objects that shouldn’t change appearance based on scene lighting.</p><p>But it also means the material doesn’t show the kind of directional shading that helps objects look more realistic.</p><p>So I needed a different material.</p><h3>3. Introducing meshStandardMaterial</h3><p>The next material I learned about was meshStandardMaterial.</p><p>This is a physically based material that responds to lighting.</p><p>Let’s replace our basic material.</p><p>Instead of:</p><pre>&lt;meshBasicMaterial color=&quot;orange&quot; /&gt;</pre><p>we use:</p><pre>&lt;meshStandardMaterial color=&quot;orange&quot; /&gt;</pre><p>That’s a small change.</p><p>But it makes a big difference.</p><p>Now our box reacts to the lights in the scene.</p><p>There’s just one problem.</p><p>If we don’t add any lights, the box will generally appear black.</p><p>Why?</p><p>Because a standard material needs illumination to reveal its surface color.</p><p>So let’s add some light.</p><h3>4. My First Light: ambientLight</h3><p>The first light I explored was ambientLight.</p><p>Ambient light provides uniform illumination throughout a scene.</p><p>It doesn’t have a specific direction, so it doesn’t create directional shading or shadows.</p><p>Here’s how to add it:</p><pre>&lt;ambientLight intensity={1} /&gt;</pre><p>Let’s break that down.</p><p>ambientLight creates the light.</p><p>intensity controls how strong it is.</p><p>If I increase the intensity, the scene generally becomes brighter.</p><p>If I decrease it, the scene becomes darker.</p><p>For example:</p><pre>&lt;ambientLight intensity={0.4} /&gt;</pre><p>provides a lower level of ambient illumination.</p><p>One important thing I learned is that ambient light doesn’t make one side of a box brighter than another based on direction.</p><p>It simply adds general illumination.</p><p>To create directional shading, I need another type of light.</p><h3>5. Introducing directionalLight</h3><p>Imagine sunlight entering your room.</p><p>One side of a box receives more light than another.</p><p>That’s the kind of effect we can create with a directional light.</p><p>In React Three Fiber:</p><pre>&lt;directionalLight<br>  position={[3, 5, 2]}<br>  intensity={2}<br>/&gt;</pre><p>Let’s understand this.</p><p>directionalLight creates directional illumination.</p><p>position={[3, 5, 2]} helps determine the direction of the light. By default, it points toward the origin.</p><p>intensity={2} controls its strength.</p><p>When this light reaches our box, different faces can receive different amounts of illumination.</p><p>That makes the box look more three-dimensional.</p><p>And unlike a point light, directional illumination doesn’t weaken just because an object is farther away.</p><p>Now let’s combine everything.</p><h3>6. Creating My First Properly Lit Box</h3><p>Here’s my complete React Three Fiber example.</p><pre>&quot;use client&quot;;</pre><pre>import { Canvas } from &quot;@react-three/fiber&quot;;<br>import { OrbitControls } from &quot;@react-three/drei&quot;;</pre><pre>function MyBox() {<br>  return (<br>    &lt;mesh&gt;<br>      &lt;boxGeometry args={[2, 2, 2]} /&gt;<br>      &lt;meshStandardMaterial color=&quot;orange&quot; /&gt;<br>    &lt;/mesh&gt;<br>  );<br>}</pre><pre>export default function Scene() {<br>  return (<br>    &lt;div style={{ height: 400 }}&gt;<br>      &lt;Canvas camera={{ position: [4, 3, 6] }}&gt;<br>        &lt;ambientLight intensity={0.4} /&gt;</pre><pre>        &lt;directionalLight<br>          position={[3, 5, 2]}<br>          intensity={2}<br>        /&gt;</pre><pre>        &lt;MyBox /&gt;</pre><pre>        &lt;OrbitControls /&gt;<br>      &lt;/Canvas&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>Now let’s understand what we’ve written.</p><p>First:</p><pre>&quot;use client&quot;;</pre><p>Since I’m using Next.js, this tells Next.js that the file is a client component.</p><p>Next:</p><pre>import { Canvas } from &quot;@react-three/fiber&quot;;</pre><p>This imports the React Three Fiber Canvas component, which provides the rendering environment.</p><p>Then:</p><pre>import { OrbitControls } from &quot;@react-three/drei&quot;;</pre><p>This imports the helper that lets us orbit, zoom, and pan around the scene.</p><p>Inside MyBox, we create our box.</p><pre>&lt;boxGeometry args={[2, 2, 2]} /&gt;</pre><p>This creates a box that’s 2 units wide, 2 units tall, and 2 units deep.</p><p>Next:</p><pre>&lt;meshStandardMaterial color=&quot;orange&quot; /&gt;</pre><p>This gives the box a material that responds to light.</p><p>Now for the lighting.</p><pre>&lt;ambientLight intensity={0.4} /&gt;</pre><p>This adds a little general illumination.</p><p>Then:</p><pre>&lt;directionalLight<br>  position={[3, 5, 2]}<br>  intensity={2}<br>/&gt;</pre><p>This adds light coming from a particular direction.</p><p>Together, these lights help reveal the box’s shape.</p><p>Finally:</p><pre>&lt;OrbitControls /&gt;</pre><p>lets me inspect the box from different angles.</p><p>And the interesting part?</p><p>I haven’t changed the box geometry at all.</p><p>I’ve only changed how its surface responds to lighting.</p><h3>7. Understanding Roughness</h3><p>After creating my lit box, I discovered another material property called roughness.</p><p>For example:</p><pre>&lt;meshStandardMaterial<br>  color=&quot;orange&quot;<br>  roughness={0.5}<br>/&gt;</pre><p>Roughness controls how smoothly or diffusely a surface reflects light.</p><p>A low roughness value means a smoother surface with sharper reflections.</p><p>A high roughness value means a rougher surface with more diffuse reflections.</p><p>The value normally ranges from 0 to 1.</p><p>For example:</p><pre>roughness={0}</pre><p>represents a very smooth surface.</p><p>While:</p><pre>roughness={1}</pre><p>represents a very rough surface.</p><p>This is useful when creating materials that resemble polished plastic, rough stone, or other kinds of surfaces.</p><h3>8. Understanding Metalness</h3><p>Another property I discovered was metalness.</p><p>For example:</p><pre>&lt;meshStandardMaterial<br>  color=&quot;orange&quot;<br>  metalness={1}<br>/&gt;</pre><p>Metalness controls whether the material behaves more like a metal or a nonmetal.</p><p>A value of 0 represents a nonmetal material.</p><p>A value of 1 represents a metallic material.</p><p>But here’s something important I learned.</p><p><strong>Setting metalness to 1 doesn’t automatically make an object look like shiny metal.</strong></p><p>A metallic material needs something to reflect.</p><p>Without a suitable environment, the result might look darker or less realistic than expected.</p><p>That’s why realistic 3D rendering often uses environment maps along with lighting.</p><p>For now, I’m focusing on understanding what the material properties do.</p><h3>9. Does Adding Light Automatically Create Shadows?</h3><p>I also learned that illuminating an object isn’t the same as making it cast a visible shadow.</p><p>In React Three Fiber, shadows need to be configured.</p><p>For example:</p><pre>&lt;Canvas shadows&gt;</pre><p>enables shadow rendering.</p><p>Then:</p><pre>&lt;directionalLight castShadow /&gt;</pre><p>allows the directional light to cast shadows.</p><p>And:</p><pre>&lt;mesh castShadow&gt;</pre><p>allows a mesh to cast shadows.</p><p>We also need a surface that can receive them.</p><p>So I’ll leave detailed shadow configuration for another lesson.</p><p>Today, I want to focus on understanding illumination and materials.</p><h3>10. Why This Matters in Real 3D Applications</h3><p>Lighting and materials are important in almost every 3D application.</p><p>Think about product visualization.</p><p>A plastic bottle and a metal container should look different, even if they have similar shapes.</p><p>Or think about architectural visualization.</p><p>Lighting helps reveal the structure of walls, furniture, and rooms.</p><p>In 3D medical model viewers, carefully chosen materials and lighting can help users understand surface shape and orientation.</p><p>And that’s why I’m learning these concepts gradually.</p><p>Before creating complex scenes, I want to understand how the basic building blocks work.</p><h3>What I Learned on Day 11</h3><p>Today, I learned that:</p><ul><li>Geometry defines the shape of an object.</li><li>Materials control how its surface appears.</li><li>meshBasicMaterial doesn&#39;t respond to scene lighting.</li><li>meshStandardMaterial responds to lighting.</li><li>ambientLight provides uniform illumination.</li><li>directionalLight creates directional illumination.</li><li>roughness controls the sharpness of surface reflections.</li><li>metalness controls whether a material behaves like a metal or nonmetal.</li><li>Shadows require additional configuration.</li></ul><p>But my biggest takeaway is this:</p><p><strong>The same 3D object can look completely different depending on its material and lighting.</strong></p><p>And now I understand why some of my earlier boxes looked flat.</p><p>I wasn’t doing anything wrong — I was simply using a material that doesn’t respond to lighting.</p><h3>What’s Next?</h3><p>For Day 12, I want to explore <strong>shadows in Three.js</strong>.</p><p>Now that I understand how lights illuminate objects, I want to learn how objects cast shadows onto other surfaces.</p><p>I’ll start with a simple box above a floor and gradually build a scene where the shadow changes as the light moves.</p><p>One concept at a time. 😄</p><h3>References</h3><ul><li><a href="https://threejs.org/docs/#api/en/materials/MeshBasicMaterial">Three.js MeshBasicMaterial Documentation</a></li><li><a href="https://threejs.org/docs/#api/en/materials/MeshStandardMaterial">Three.js MeshStandardMaterial Documentation</a></li><li><a href="https://threejs.org/docs/#api/en/lights/AmbientLight">Three.js AmbientLight Documentation</a></li><li><a href="https://threejs.org/docs/#api/en/lights/DirectionalLight">Three.js DirectionalLight Documentation</a></li><li><a href="https://r3f.docs.pmnd.rs/">React Three Fiber Documentation</a></li></ul><p><em>Day 11 of my Three.js learning journey — learning in public, one concept at a time.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=425d5ac8dc8a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 10 of Learning Three.js: I Finally Understand How Cameras Work in React Three Fiber!]]></title>
            <link>https://medium.com/@chiomsyndev/day-10-of-learning-three-js-i-finally-understand-how-cameras-work-in-react-three-fiber-f13ef112eb58?source=rss-39943d331ca7------2</link>
            <guid isPermaLink="false">https://medium.com/p/f13ef112eb58</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react-three-fiber]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[threejs]]></category>
            <category><![CDATA[3d-graphics]]></category>
            <dc:creator><![CDATA[Mirian Ezeamama]]></dc:creator>
            <pubDate>Mon, 26 Oct 2026 11:08:25 GMT</pubDate>
            <atom:updated>2026-10-26T11:08:25.207Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0BTDJfkIWrwkxod1KcLM9A.png" /></figure><p><em>Understanding camera position, perspective, field of view, and OrbitControls — one beginner-friendly concept at a time.</em></p><p>On Day 9 of my Three.js learning journey, I built a tiny solar system.</p><p>I learned how parent-child relationships work and how rotating a group can make an object move around another object.</p><p>But while building all these scenes, I noticed something.</p><p>We’ve been using a camera since Day 1.</p><p>Almost every example includes something like:</p><pre>&lt;Canvas camera={{ position: [4, 3, 6] }}&gt;</pre><p>And although I knew it helped us see our 3D objects, I didn’t fully understand what those numbers meant.</p><p>Why do we need a camera?</p><p>Why does moving the camera change how an object looks?</p><p>And what’s the difference between moving an object closer and changing the camera’s field of view?</p><p>So for Day 10, I decided to understand cameras properly.</p><p>Let’s start from the beginning.</p><h3>1. What Is a Camera in Three.js?</h3><p>Imagine placing a toy car on a table.</p><p>Now take out your phone and point its camera at the car.</p><p>The car exists whether you’re taking a picture or not.</p><p>But your camera determines how you see it.</p><p>If you move closer, the car appears bigger.</p><p>If you move farther away, it appears smaller.</p><p>And if you move to the other side, you see a different part of the car.</p><p>A camera in Three.js works in a similar way.</p><p>It defines the viewpoint used to render our 3D scene onto a 2D screen.</p><p>The camera doesn’t create the objects.</p><p>It doesn’t change their geometry.</p><p>It determines what we see and how the scene is projected onto the screen.</p><p>That helped me understand why a camera is so important.</p><p>Without a viewpoint, we wouldn’t know how to display our 3D world.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bEBBBnpkIhZ8nSbiun-Kkg.png" /></figure><h3>2. Understanding Camera Position</h3><p>Let’s revisit this line:</p><pre>&lt;Canvas camera={{ position: [4, 3, 6] }}&gt;</pre><p>At first, it might look complicated.</p><p>But let’s break it down.</p><p>Canvas creates our React Three Fiber rendering environment.</p><p>camera={{ ... }} provides camera settings.</p><p>And position tells React Three Fiber where to place the camera in 3D space.</p><p>The three numbers represent X, Y, and Z.</p><pre>position: [X, Y, Z]</pre><p>So:</p><pre>position: [4, 3, 6]</pre><p>means the camera is positioned 4 units along X, 3 units up along Y, and 6 units along Z.</p><p>Notice that we’re not moving the box.</p><p>We’re moving the camera.</p><p>That’s an important difference.</p><p>Imagine keeping a toy car on a table while walking around it.</p><p>The car stays in the same place.</p><p>Only your viewpoint changes.</p><p>That’s what camera movement allows us to do in Three.js.</p><h3>3. What Is a PerspectiveCamera?</h3><p>When I started reading about Three.js cameras, I encountered a term called PerspectiveCamera.</p><p>The name sounded complicated.</p><p>But the basic idea is something we experience every day.</p><p>Objects appear smaller when they’re farther away.</p><p>Think about looking at two identical cars.</p><p>One is parked right beside you.</p><p>The other is far down the road.</p><p>The distant car looks smaller, even though both cars have the same real-world dimensions.</p><p>That’s perspective.</p><p>A PerspectiveCamera creates this familiar effect in our 3D scene.</p><p>And React Three Fiber normally creates a perspective camera for us when we use Canvas.</p><p>That’s why we can write:</p><pre>&lt;Canvas camera={{ position: [4, 3, 6] }}&gt;</pre><p>without manually constructing a camera.</p><p>Three.js also has an OrthographicCamera, which uses a different projection.</p><p>With orthographic projection, objects don’t become smaller simply because they’re farther from the camera.</p><p>That’s useful for certain technical views, diagrams, and modelling tools.</p><p>But for today, I’m focusing on perspective cameras.</p><h3>4. What Is Field of View?</h3><p>Another camera setting I encountered was fov.</p><p>FOV stands for <strong>field of view</strong>.</p><p>Think of it as how wide the camera can see.</p><p>Imagine looking through a narrow tube.</p><p>You can only see a small part of what’s in front of you.</p><p>Now imagine removing the tube.</p><p>You can see a much wider area.</p><p>That’s similar to changing a camera’s field of view.</p><p>In Three.js, a perspective camera’s fov value describes its vertical viewing angle in degrees.</p><p>For example:</p><pre>&lt;Canvas camera={{ position: [4, 3, 6], fov: 55 }}&gt;</pre><p>Here, we’re using a field of view of 55 degrees.</p><p>A smaller FOV generally makes objects appear larger in the image when the camera stays in the same place.</p><p>A larger FOV shows more of the scene, making objects appear smaller.</p><p>Try changing:</p><pre>fov: 55</pre><p>to:</p><pre>fov: 30</pre><p>Then try:</p><pre>fov: 90</pre><p>Notice how much of the scene fits into the view.</p><p>One thing I learned is that changing FOV doesn’t actually resize the 3D object.</p><p>It changes the camera’s projection.</p><h3>5. Let’s Create a Scene with Camera Settings</h3><p>Now let’s write a simple example.</p><pre>&quot;use client&quot;;</pre><pre>import { Canvas } from &quot;@react-three/fiber&quot;;</pre><pre>function MyBox() {<br>  return (<br>    &lt;mesh&gt;<br>      &lt;boxGeometry args={[2, 1, 1]} /&gt;<br>      &lt;meshBasicMaterial color=&quot;orange&quot; /&gt;<br>    &lt;/mesh&gt;<br>  );<br>}</pre><pre>export default function CameraScene() {<br>  return (<br>    &lt;div style={{ height: 400 }}&gt;<br>      &lt;Canvas<br>        camera={{<br>          position: [4, 3, 6],<br>          fov: 55,<br>        }}<br>      &gt;<br>        &lt;axesHelper args={[3]} /&gt;<br>        &lt;MyBox /&gt;<br>      &lt;/Canvas&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>Let’s understand the important parts.</p><p>First:</p><pre>&quot;use client&quot;;</pre><p>Since I’m using Next.js, this tells Next.js that the file is a client component.</p><p>Next:</p><pre>import { Canvas } from &quot;@react-three/fiber&quot;;</pre><p>Canvas provides the environment where our 3D scene is rendered.</p><p>Then:</p><pre>function MyBox() {</pre><p>We create a React component to describe our box.</p><p>Inside it:</p><pre>&lt;boxGeometry args={[2, 1, 1]} /&gt;</pre><p>creates a box 2 units wide, 1 unit tall, and 1 unit deep.</p><p>And:</p><pre>&lt;meshBasicMaterial color=&quot;orange&quot; /&gt;</pre><p>gives it an orange appearance without requiring lights.</p><p>Now for the camera:</p><pre>camera={{<br>  position: [4, 3, 6],<br>  fov: 55,<br>}}</pre><p>This tells React Three Fiber where to place the camera and what field of view to use.</p><p>Finally:</p><pre>&lt;axesHelper args={[3]} /&gt;</pre><p>displays the X, Y, and Z axes to help us understand orientation.</p><p>The result is a simple 3D box viewed through a perspective camera.</p><h3>6. Camera Position Versus Camera Direction</h3><p>Here’s another important thing I learned.</p><p>Positioning a camera isn’t the same as telling it where to look.</p><p>Imagine standing beside a car with your phone.</p><p>Even if you’re close to the car, you won’t capture it if your phone is pointing in the opposite direction.</p><p>A Three.js camera has both a position and an orientation.</p><p>And we can aim it at a point using:</p><pre>camera.lookAt(0, 0, 0);</pre><p>This tells the camera to face the world origin.</p><p>It changes the camera’s orientation without moving its position.</p><p>In our basic Canvas examples, React Three Fiber sets up the automatically created camera to look toward the origin.</p><p>So we usually don’t need to call lookAt() ourselves.</p><p>But it’s useful to understand because we’ll eventually want to control where our cameras point.</p><h3>7. What Is OrbitControls?</h3><p>After learning about camera position and field of view, I wanted something more interactive.</p><p>What if I could click and drag to inspect my box from different angles?</p><p>That’s where OrbitControls comes in.</p><p>OrbitControls is a helper available through @react-three/drei.</p><p>It allows us to interact with the camera using mouse or touch controls.</p><p>Here’s a simple example:</p><pre>&quot;use client&quot;;</pre><pre>import { Canvas } from &quot;@react-three/fiber&quot;;<br>import { OrbitControls } from &quot;@react-three/drei&quot;;</pre><pre>function MyBox() {<br>  return (<br>    &lt;mesh&gt;<br>      &lt;boxGeometry args={[2, 1, 1]} /&gt;<br>      &lt;meshBasicMaterial color=&quot;orange&quot; /&gt;<br>    &lt;/mesh&gt;<br>  );<br>}</pre><pre>export default function CameraScene() {<br>  return (<br>    &lt;div style={{ height: 400 }}&gt;<br>      &lt;Canvas camera={{ position: [4, 3, 6], fov: 55 }}&gt;<br>        &lt;axesHelper args={[3]} /&gt;<br>        &lt;MyBox /&gt;<br>        &lt;OrbitControls /&gt;<br>      &lt;/Canvas&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>Let’s focus on the new lines.</p><p>First:</p><pre>import { OrbitControls } from &quot;@react-three/drei&quot;;</pre><p>This imports the OrbitControls helper.</p><p>Then:</p><pre>&lt;OrbitControls /&gt;</pre><p>adds interactive camera controls to our scene.</p><p>On a desktop computer, I can usually drag with the left mouse button to orbit around the object, scroll to zoom, and use right-drag to pan.</p><p>Here’s something important.</p><p>When I drag to orbit, the box itself isn’t necessarily rotating.</p><p>The camera is moving around it.</p><p>That distinction matters.</p><p>The object stays in the scene while I change my viewpoint.</p><h3>8. Why Camera Knowledge Matters</h3><p>At first, learning about cameras might seem less exciting than making a box move or spin.</p><p>But cameras are essential in real 3D applications.</p><p>Imagine creating a 3D product viewer.</p><p>Users need to inspect the product from different angles.</p><p>Or imagine creating a game.</p><p>The camera might follow a character as it moves.</p><p>Or consider a 3D medical model viewer.</p><p>A clinician may need to rotate the view, zoom in on a particular area, or inspect a model from a specific direction.</p><p>Understanding cameras helps us build these kinds of interactions.</p><p>And now I can see why we’ve been using cameras since Day 1.</p><h3>What I Learned on Day 10</h3><p>Today, I learned that:</p><ul><li>A camera determines how we view a 3D scene.</li><li>Camera position uses X, Y, and Z coordinates.</li><li>A PerspectiveCamera makes distant objects appear smaller.</li><li>FOV means field of view.</li><li>A smaller FOV generally creates a more zoomed-in appearance.</li><li>A larger FOV shows more of the scene.</li><li>lookAt() changes the direction a camera faces.</li><li>OrbitControls lets users orbit, zoom, and pan around a 3D scene.</li><li>Moving a camera is different from moving or rotating an object.</li></ul><p>But my biggest takeaway is this:</p><p><strong>The camera doesn’t change what the 3D object is. It changes how we see it.</strong></p><p>That helped me understand why the same box can look completely different depending on where the camera is placed and how it’s configured.</p><h3>What’s Next?</h3><p>For Day 11, I want to explore <strong>lighting and materials in Three.js</strong>.</p><p>So far, we’ve mostly used meshBasicMaterial, which doesn&#39;t require lighting.</p><p>Now I want to understand how light changes the appearance of 3D objects, why some materials react to light and others don’t, and how to create a scene with more realistic depth.</p><p>One concept at a time.</p><h3>References</h3><ul><li><a href="https://threejs.org/docs/#api/en/cameras/PerspectiveCamera">Three.js PerspectiveCamera Documentation</a></li><li><a href="https://threejs.org/docs/#api/en/cameras/Camera">Three.js Camera Documentation</a></li><li><a href="https://threejs.org/docs/#examples/en/controls/OrbitControls">Three.js OrbitControls Documentation</a></li><li><a href="https://r3f.docs.pmnd.rs/">React Three Fiber Documentation</a></li></ul><p><em>Day 10 of my Three.js learning journey — learning in public, one concept at a time.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f13ef112eb58" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>