<?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 Mimi Scott on Medium]]></title>
        <description><![CDATA[Stories by Mimi Scott on Medium]]></description>
        <link>https://medium.com/@mimiscott94?source=rss-c65bc07c51a8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*o5s5MPCQYl23aMZkdwE9WA.png</url>
            <title>Stories by Mimi Scott on Medium</title>
            <link>https://medium.com/@mimiscott94?source=rss-c65bc07c51a8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 19:25:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mimiscott94/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[Bouncing Shapes: A Three.js Tutorial]]></title>
            <link>https://medium.com/@mimiscott94/bouncing-shapes-a-three-js-tutorial-a867688c72a?source=rss-c65bc07c51a8------2</link>
            <guid isPermaLink="false">https://medium.com/p/a867688c72a</guid>
            <category><![CDATA[graphics]]></category>
            <category><![CDATA[threejs]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Mimi Scott]]></dc:creator>
            <pubDate>Fri, 26 Jan 2018 20:29:40 GMT</pubDate>
            <atom:updated>2018-01-26T20:29:40.361Z</atom:updated>
            <content:encoded><![CDATA[<p>WebGL is a comprehensive API for creating 2D and 3D graphics in JavaScript, but it can feel a bit overwhelming and hard to manage. Three.js to the rescue!</p><p>Three.js is a wrapper library for WebGL that is easy to use and contains plenty of great tools to create complex graphics scenes for your projects. In this post I’m going to explain how I built a simple web app that manipulates the shape and movement of an object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WT49LCI2ceszYl-i1eqNFg.png" /></figure><p>All of the code for this tutorial can be found on my <a href="https://github.com/mimi1694/bouncing-shapes">Github page</a>, and the final product <a href="http://bouncing-shapes.herokuapp.com/">here</a>.</p><p>(Side note, I used Bootstrap to add some simple CSS to my page)</p><p>For the purposes of this tutorial, I am going to focus on the file shapes.js. The other files are index.html, styles.css, an three.js. Three.js can be downloaded from <a href="http://threejs.org/">threejs.org</a>, and if you so choose you can create your own index.html or follow along with mine. When writing your own html, don’t forget to include link(s) to your stylesheets in your &lt;head&gt; , and the following &lt;script&gt; tags at the top of your &lt;body&gt; tag. I have also included two forms and a button to control the functionality of the app.</p><p>The first thing to do in shapes.js is to set up the scene. In order to view your items, you must add a few things:</p><ul><li>The scene: this initializes the space you are going to be working in</li><li>The renderer: renders objects in your scenehow</li><li>A camera: the view point from which you’ll “look” at your object</li><li>Light: with light, your objects will appear dark</li></ul><pre>const scene = new THREE.Scene()<br>const renderer = new THREE.WebGLRenderer()<br>const camera = new THREE.PerspectiveCamera(30, <br>               window.innerWidth / window.innerHeight, 0.1, 1000)<br>const light = new THREE.DirectionalLight()</pre><pre>scene.background = (new THREE.Color(&#39;white&#39;))</pre><pre>renderer.setSize(3 * window.innerWidth / 4, <br>                 3 * window.innerHeight / 4)</pre><pre>document.body.appendChild(renderer.domElement)<br>camera.position.z = 17<br>light.position.set(-1, 1, 1)</pre><p>I have set the scene background to white, and the renderer to only 3/4 the size of the page.</p><p>This way, my scene will be responsive to the size of the window, and the perspective will always stay the same instead of getting wonky when someone changes the window size.</p><p>The camera can also be moved closer or further away depending on its position.</p><p>Think of positioning in terms of a 3-D axis. Almost everything in Three.js is going to be rendered on its own 3-D grid where the x axis goes up and down, y goes to the sides, and z comes towards you or away.</p><p>I have also set the light to be in the upper left corner of the quadrant towards the camera. You can have as many lights as you’d like in your scene, and Three.js has a few different kinds depending on the desired effect. Ambient light globally lights all objects equally. I’ve used a directional light, so you’ll be able to tell which way the light is coming from once we’ve rendered an object based on how the light hits the object.</p><p>Before we can plop an object in our scene, we need to make one! Three.js comes with plenty of pre-set geometries to make different shapes. In this tutorial, we’ll be making a sphere, a cube, and a torus.</p><p>BoxGeometry takes a width, height, and depth as parameters, SphereGeometry takes a radius, width segments and height segments as parameters, and TorusGeometry takes radius, tube, radialSegments, tubularSegments, arc as its parameters.</p><p>Let’s create these shapes by making three variables — one to hold each.</p><pre>let box = new THREE.BoxGeometry(1, 1, 1)<br>let sphere = new THREE.SphereGeometry(0.5, 32, 32)<br>let torus = new THREE.TorusGeometry(0.5, 0.25, 32, 32, 2 * Math.PI)</pre><p>A Mesh is a collection of vertices, edges, and faces that come together to make a geometry (like THREE.BoxGeometry). Three.js makes creating an object easier for us by having pre-built mesh materials which add surface attributes to those faces.</p><p>Let’s create 3 — a MeshPhongMaterial, MeshLambertMaterial, and MeshBasicMaterial.</p><p>While there are nuances to each material, basically Phong and Lambert materials need light to be seen. However, Phong has specular color — specular light is the shiny spot on an object that indicates to us surface shape and reflectivity — and Lambert does not. A Basic material looks the same no matter the lighting in the space. So let’s make them!</p><pre>let phong = new THREE.MeshPhongMaterial({<br>   color: ‘pink’,<br>   emissive: 0,<br>   specular: 0x070707,<br>   shininess: 100<br>})</pre><pre>let basic = new THREE.MeshBasicMaterial({<br>   color: ‘pink’<br>})</pre><pre>let lambert = new THREE.MeshPhongMaterial({<br>   color: ‘pink’,<br>   reflectivity: .5,<br>   refractionRatio: 1<br>})</pre><p>So now we have geometries and materials, and can put them together to form an object. In this scene, we’re going to only make one object and update properties on it. So let’s initialize the variables obj, currentShape, and currentMesh. To begin, we can set the currentShape to box currentMesh to phong, and obj to a new THREE.Mesh(). When that’s done, we can add the light and obj to the scene. This code will look like the below:</p><pre>let obj, currentShape, currentMesh<br>currentShape = box<br>currentMesh = phong</pre><pre>obj = new THREE.Mesh(currentShape, currentMesh)</pre><pre>scene.add(light)<br>scene.add(obj)</pre><p>Now we have a scene that has a pink cube in the middle of it — but we still can’t see anything! That’s because we need to use our renderer to show the scene’s child objects (the light and obj).</p><p>Create a function called animate. Inside animate, we are going to call the method requestAnimationFrame() and pass it animate, like so:</p><pre>let animate = () =&gt; {<br>   requestAnimationFrame(animate)<br>}</pre><p>requestAnimationFrame() is a method on your window that takes a callback as an argument every time the window repaints itself. This happens about 60 times per second, and is called when you want to repeatedly change (or repaint) your window.</p><p>Inside animate we are going to add functionality to obj. When we open our app, we want to see that our shape can move, so let’s set the obj.rotation.y to increase every time the window repaints itself. This will create a seamless rotation effect. Check it out by adding this line under requestAnimationFrame(animate)</p><pre>obj.rotation.y += 0.01</pre><p>Now, let’s make it so that when our button is clicked, the shape starts moving towards the top of the scene, then moves the other direction when it gets too high. To control this, I’ve included a variable called bounceControl that toggles each time the button is clicked.</p><p>When the button is clicked, stop the rotation (it messes with the following translation) and translate obj on the path of new vector that points between the top and bottom poles of the scene. This looks like the following:</p><p>obj.translateOnAxis(new THREE.Vector3(0, 1, 0).normalize(), 0.1)</p><p>You can think of vectors like imaginary lines in the space. Vector objects take in (x, y, z) parameters — This vector has no x or z variables ,and so it lies solely on the y axis. The second variable in the method translateOnAxis is how much obj’s position will change at each call of animate. I have chosen a small number so obj will move relatively slowly.</p><p>Remember how I said we couldn’t see anything because nothing had been rendered? At the bottom of all this logic call renderer.render(scene, camera). Since scene has obj and light as children, everything we’ve just made will be put in the scene, and the camera will allow us to view it.</p><p>The whole animate function looks like the below:</p><pre>let bounceControl = false<br>let up = true<br>let animate = () =&gt; {<br>   requestAnimationFrame(animate)<br>   obj.rotation.y += 0.01<br>   if (bounceControl) {<br>      obj.rotation.x = 0<br>      obj.rotation.y = 0<br>      if (up) {<br>         obj.translateOnAxis(new THREE.Vector3(0, 1, 0).normalize(),<br>                             0.1)<br>         if (obj.position.y &gt; 3.4) {<br>            up = false<br>         }<br>      }<br>      else if (!up) {<br>         obj.translateOnAxis(new THREE.Vector3(0, 1, 0).normalize(),  <br>                             -0.1)<br>         if (obj.position.y &lt; -3.4) {<br>             up = true<br>         }<br>      }<br>      else {<br>         obj.position.set(0, 0, 0)<br>      }<br>   }<br>   renderer.render(scene, camera)<br>}</pre><p>Now what? We haven’t called animate! Wrap animate() in window.onload like the following:</p><pre>window.onload = () =&gt; {<br>   animate()<br>}</pre><p>Lastly, add the functionality that responds to our user. You can do this however you’d like, but I used a button to trigger the ‘bounce’ and a form to change the the shape and material. You can do this by setting obj.geometry and obj.material to the variables we created earlier. However, when you want to change a material or geometry, you need to call obj.material.needsUpdate = true and obj.geometry.bufferNeedsUpdate = true, respectively. I used a switch case in the form.onchange method to control the geometry and material changes. I then used the button.onlick method to toggle bounceControl which affects the bounce direction in the animate() function. Here’s my full window.onload() call:</p><pre>window.onload = () =&gt; {<br>   document.getElementById(‘shape-form’).onchange = (evt) =&gt; {<br>      switch (evt.target.value) {<br>         case ‘box’:<br>            currentShape = box<br>            break<br>         case ‘sphere’:<br>            currentShape = sphere<br>            break<br>         case ‘torus’:<br>            currentShape = torus<br>            break<br>         default:<br>            currentShape = box<br>            break<br>      }<br>      obj.geometry = currentShape<br>      obj.geometry.buffersNeedUpdate = true<br>   }</pre><pre>   document.getElementById(‘mesh-form’).onchange = (evt) =&gt; {<br>      switch (evt.target.value) {<br>         case ‘phong’:<br>            currentMesh = phong<br>            break<br>         case ‘basic’:<br>            currentMesh = basic<br>            break<br>         case ‘lambert’:<br>            currentMesh = lambert<br>            break<br>         default:<br>            currentMesh = box<br>            break<br>      }<br>      obj.material = currentMesh<br>      obj.material.needsUpdate = true<br>   }</pre><pre>   let bounce = document.getElementById(‘bounce’)<br>   bounce.innerHTML = ‘BOUNCE!’</pre><pre>   bounce.onclick = () =&gt; {<br>      if (bounceControl === false) {<br>         bounceControl = true<br>         bounce.innerHTML = ‘STOP’<br>      }<br>      else {<br>         bounceControl = false<br>         bounce.innerHTML = ‘BOUNCE!’<br>      }<br>   }<br>   animate()<br>}</pre><p>Now you should have a project that creates a scene, puts an object and light into them, manipulates the object’s attributes, and makes it move!</p><p>As you can see, Three.js made all of that code simpler by having geometries, materials, lights, and more at the ready for us to use instead of us having to build them ourselves.</p><p>Have fun playing with this code, manipulating your own objects, and seeing all the awesome things Three.js can do!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a867688c72a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>