Three.js – Creating Text

Three.js – Creating Text ”; Previous Next Often you need to add text to your scene. In this chapter, let”s see how to add 2D and 3D text to our scene. Draw Text to Canvas and Use as a Texture This is the easiest way to add 2D text to your scene. you can create canvas using JavaScript andd add it to the dom. const canvas = document.createElement(”canvas”) const context = canvas.getContext(”2d”) The code above creates a canvas element, and we set the context to 2d. The canvas.getContext() method returns an object that provides methods and properties for drawing on the canvas, which it can use to draw text, lines, boxes, circles, and more. context.fillStyle = ”green” context.font = ”60px sans-serif context.fillText(”Hello World!”, 0, 60) The fillText() is a method of a 2D drawing context. The fillText() method allows you to draw a text string at a coordinate with the fill (color) derived from the fillStyle you provided. You can set the font of the text using the font property. The above code set the font to 60-pixel-tall san-serif and the fill style to green. The text ”Hello, World!” is drawn starting at the coordinates (0, 60). // canvas contents are used for a texture const texture = new THREE.Texture(canvas) texture.needsUpdate = true To create a texture from a canvas element, we need to create a new instance of THREE.Texture and pass in the canvas element we made. The code above creates a texture using the canvas (in this case, our text). The needsUpdate parameter of the texture is set to true. It informs Three.js that our canvas texture has changed and needs to be updated the next time the scene is rendered. Now, create a plane geometry and add this as a texture to the material. var material = new THREE.MeshBasicMaterial({ map: texture, side: THREE.DoubleSide, }) material.transparent = true var mesh = new THREE.Mesh(new THREE.PlaneGeometry(50, 10), material) Using Text Geometry THREE.TextGeometry is another type of geometry that generates text as a single geometry. It takes two arguments, text – the text you want to render, and other parameters. Parameters font − This is the name of the font. size − Size of the text. Default is 100. height − The height property defines the depth of the text; in other words, how far the text extrudes to make it 3D. This defaults to 50. curveSegments − Number of points on the curves. Default is 12. bevelEnabled − A bevel provides a smooth transition from the front of the text to the side. If you set this value to true, it adds a bevel to the rendered text. By default, it is false. bevelThickness − If you”ve set bevelEnabled to true, it defines how deep the bevel is. Default is 10. bevelSize − It determines how high the bevel is. Default is equal to 8. bevelOffset − How far from text outline bevel starts. Default is 0. bevelSegments − The number of bevel segments. Default is 3. You need to use THREE.FontLoader to load fonts from their typeface.json files. const loader = new THREE.FontLoader() loader.load(”fonts/helvetiker_regular.typeface.json”, function (font) { const geometry = new THREE.TextGeometry(”Hello Three.js!”, { font: font, size: 3, height: 0.2, curveSegments: 12, bevelEnabled: false, bevelThickness: 0.5, bevelSize: 0.3, bevelOffset: 0, bevelSegments: 5, }) }) Now, you should add some material to it and create a mesh. const material = new THREE.MeshFaceMaterial([ new THREE.MeshPhongMaterial({ color: 0xff22cc, flatShading: true, }), // front new THREE.MeshPhongMaterial({ color: 0xffcc22 }), // side ]) const mesh = new THREE.Mesh(geometry, material) mesh.name = ”text” scene.add(mesh) Note − There is one thing you need to take into account when working with THREE.TextGeometry and materials. It can take two materials as an array: one for the front of rendered text and another for the side of the text. If you just pass in one material, it gets applied to both the front and the side. Example Now, you can see the text rendered to the scene. Check out the following example. 2d-text.html Live Demo <!DOCTYPE html> <html> <head> <meta charset=”UTF-8″ /> <meta http-equiv=”X-UA-Compatible” content=”ie=edge” /> <meta name=”viewport” content=”width=device-width, initial-scale=1.0″ /> <title>Three.js – 2d text</title> <style> * { margin: 0; padding: 0; box-sizing: border-box; font-family: -applesystem, BlinkMacSystemFont, ”Segoe UI”, Roboto, Oxygen, Ubuntu, Cantarell, ”Open Sans”, ”Helvetica Neue”, sans-serif; } html, body { height: 100vh; width: 100vw; } #threejs-container { position: block; width: 100%; height: 100%; } </style> <script src=”https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js”></script> <script src=”https://cdnjs.cloudflare.com/ajax/libs/dat-gui/0.7.7/dat.gui.js”></script> </head> <body> <div id=”threejs-container”></div> <script type=”module”> // Adding 2d text to Three.js scene // Writing on canvas and then adding the canvas as a texture to material // GUI const gui = new dat.GUI() // sizes let width = window.innerWidth let height = window.innerHeight const size = 256 const container = document.querySelector(”#threejs-container”) const canvas = document.createElement(”canvas”), ctx = canvas.getContext(”2d”) function changeCanvas() { ctx.font = ”20pt Arial” ctx.fillStyle = ”white” ctx.fillRect(0, 0, canvas.width, canvas.height) ctx.fillStyle = ”black” ctx.textAlign = ”center” ctx.textBaseline = ”middle” ctx.fillText(”Tutorialspoint!”, canvas.width / 2, canvas.height / 2) } // scene const scene = new THREE.Scene() scene.background = new THREE.Color(0x262626) // lights const ambientLight = new THREE.AmbientLight(0xffffff, 1) scene.add(ambientLight) const pointLight = new THREE.PointLight(0xffffff, 0.5) pointLight.position.x = 20 pointLight.position.y = 30 pointLight.position.z = 40 scene.add(pointLight) // camera const camera = new THREE.PerspectiveCamera(70, width / height, 1, 1000) camera.position.z = 500 scene.add(camera) // renderer const renderer = new THREE.WebGL1Renderer({ antialias: true }) renderer.setSize(width, height) renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)) container.append(renderer.domElement) renderer.render(scene, camera) // cube const texture = new THREE.Texture(canvas) const material = new THREE.MeshStandardMaterial({ map: texture }) const geometry = new THREE.BoxGeometry(200, 200, 200) const mesh = new THREE.Mesh(geometry, material) scene.add(mesh) canvas.width = canvas.height = size // responsiveness window.addEventListener(”resize”, () => { width = window.innerWidth height = window.innerHeight camera.aspect = width / height camera.updateProjectionMatrix() renderer.setSize(window.innerWidth, window.innerHeight) renderer.render(scene, camera) }) //

Three.js – Drawing Lines

Three.js – Drawing Lines ”; Previous Next You have learned about quite a lot of materials in Three.js. Now let”s see some unique materials used in drawing lines. We can draw various shapes and patterns using lines. Using BufferGeometry THREE.BufferGeometry is the base class of all the built-in geometries in Three.js. You can create your geometry by passing an array of vertices of the geometry. Learn more about BufferGeometry here. const points = [] points.push(new THREE.Vector3(-10, 0, 0)) points.push(new THREE.Vector3(0, -10, 0)) points.push(new THREE.Vector3(10, 0, 0)) These are some additional elements Three.js provides us to create our geometries. THREE.Vector3(x, y, z) – It makes a point in 3D space. In the above code, we are adding 3 points to the points array. const geometry = new THREE.BufferGeometry().setFromPoints(points) THREE.BufferGeometry(), as mentioned before it creates our geometry. We use the setFromPoints method to set the geometry using the array of points. Note − Lines are drawn between each consecutive pair of vertices, but not between the first and last (the line is not closed.) const material = new THREE.LineBasicMaterial({ // for normal lines color: 0xffffff, linewidth: 1, linecap: ”round”, //ignored by WebGLRenderer linejoin: ”round”, //ignored by WebGLRenderer }) // or const material = new THREE.LineDashedMaterial({ // for dashed lines color: 0xffffff, linewidth: 1,scale: 1, dashSize: 3, gapSize: 1, }) These are the unique materials for lines. You can use any one of THREE.LineBasicMaterial or THREE.LineDashedMaterial. const line = new THREE.Line(geometry, material) Example Now, instead of using THREE.Mesh, we use THREE.Line for drawing lines. Now, you see a “V” shape drawn using lines on the screen. linebasic.html Live Demo <!DOCTYPE html> <html lang=”en”> <head> <meta charset=”UTF-8″ /> <meta http-equiv=”X-UA-Compatible” content=”ie=edge” /> <meta name=”viewport” content=”width=device-width, initial-scale=1.0″ /> <title>Three.js – Line basic</title> <style> * { margin: 0; padding: 0; box-sizing: border-box; font-family: -applesystem, BlinkMacSystemFont, ”Segoe UI”, Roboto, Oxygen, Ubuntu, Cantarell, ”Open Sans”, ”Helvetica Neue”, sans-serif; } html, body { height: 100vh; width: 100vw; } #threejs-container { position: block; width: 100%; height: 100%; } </style> <script src=”https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js”></script> <script src=”https://cdnjs.cloudflare.com/ajax/libs/dat-gui/0.7.7/dat.gui.js”></script> </head> <body> <div id=”threejs-container”></div> <script type=”module”> // Creating a line using LineBasicMaterial // GUI const gui = new dat.GUI() // sizes let width = window.innerWidth let height = window.innerHeight // scene const scene = new THREE.Scene() scene.background = new THREE.Color(0x262626) // camera const camera = new THREE.PerspectiveCamera(45, width / height, 0.1, 100) camera.position.set(0, 0, 50) camera.lookAt(0, 0, 0) const camFolder = gui.addFolder(”Camera”) camFolder.add(camera.position, ”z”, 10, 100) camFolder.open() // Line const points = [] points.push(new THREE.Vector3(-10, 0, 0)) points.push(new THREE.Vector3(0, -20, 0)) points.push(new THREE.Vector3(10, 0, 0)) const folders = [gui.addFolder(”Poin 1”), gui.addFolder(”Poin 2”), gui.addFolder(”Poin 3”)] folders.forEach((folder, i) => { folder.add(points[i], ”x”, -30, 30, 1).onChange(redraw) folder.add(points[i], ”y”, -30, 30, 1).onChange(redraw) folder.add(points[i], ”z”, -30, 30, 1).onChange(redraw) folder.open() }) const geometry = new THREE.BufferGeometry().setFromPoints(points) const material = new THREE.LineBasicMaterial({ color: 0xffffff, linewidth: 2 }) const line = new THREE.Line(geometry, material) line.position.set(0, 10, 0) scene.add(line) function redraw() { let newGeometry = new THREE.BufferGeometry().setFromPoints(points) line.geometry.dispose() line.geometry = newGeometry } // responsiveness window.addEventListener(”resize”, () => { width = window.innerWidth height = window.innerHeight camera.aspect = width / height camera.updateProjectionMatrix() renderer.setSize(window.innerWidth, window.innerHeight) renderer.render(scene, camera) }) // renderer const renderer = new THREE.WebGL1Renderer() renderer.setSize(width, height) renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)) // animation function animate() { requestAnimationFrame(animate) renderer.render(scene, camera) } // rendering the scene const container = document.querySelector(”#threejs-container”) container.append(renderer.domElement) renderer.render(scene, camera) animate() </script> </body> </html> Output Example You can create any type of geometry wireframe using lines by specifying the vertices. Check out the following example where we are drawing dashed lines. dashedline.html Live Demo <!DOCTYPE html> <html lang=”en”> <head> <meta charset=”UTF-8″ /> <meta http-equiv=”X-UA-Compatible” content=”ie=edge” /> <meta name=”viewport” content=”width=device-width, initial-scale=1.0″ /> <title>Three.js – Dashed line</title> <style> * { margin: 0; padding: 0; box-sizing: border-box; font-family: -applesystem, BlinkMacSystemFont, ”Segoe UI”, Roboto, Oxygen, Ubuntu, Cantarell, ”Open Sans”, ”Helvetica Neue”, sans-serif; } html, body { height: 100vh; width: 100vw; } #threejs-container { position: block; width: 100%; height: 100%; } </style> <script src=”https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js”></script> <script src=”https://cdnjs.cloudflare.com/ajax/libs/dat-gui/0.7.7/dat.gui.js”></script> </head> <body> <div id=”threejs-container”></div> <script type=”module”> // Creating dashed line using LineDashedMaterial // GUI const gui = new dat.GUI() // sizes let width = window.innerWidth let height = window.innerHeight // scene const scene = new THREE.Scene() scene.background = new THREE.Color(0x262626) // camera const camera = new THREE.PerspectiveCamera(45, width / height, 0.1, 100) camera.position.set(0, 0, 50) camera.lookAt(0, 0, 0) const camFolder = gui.addFolder(”Camera”) camFolder.add(camera.position, ”z”, 10, 100) camFolder.open() // Line const points = [] points.push(new THREE.Vector3(-10, 0, 0)) points.push(new THREE.Vector3(0, -20, 0)) points.push(new THREE.Vector3(10, 0, 0)) const folders = [gui.addFolder(”Poin 1”), gui.addFolder(”Poin 2”), gui.addFolder(”Poin 3”)] folders.forEach((folder, i) => { folder.add(points[i], ”x”, -30, 30, 1).onChange(redraw) folder.add(points[i], ”y”, -30, 30, 1).onChange(redraw) folder.add(points[i], ”z”, -30, 30, 1).onChange(redraw) folder.open() }) const geometry = new THREE.BufferGeometry().setFromPoints(points) const material = new THREE.LineDashedMaterial({ color: 0xffffff, linewidth: 2, scale: 1, dashSize: 3, gapSize: 2 }) const line = new THREE.Line(geometry, material) line.computeLineDistances() line.position.set(0, 10, 0) scene.add(line) console.log(line) function redraw() { let newGeometry = new THREE.BufferGeometry().setFromPoints(points) line.geometry.dispose() line.geometry = newGeometry } // responsiveness window.addEventListener(”resize”, () => { width = window.innerWidth height = window.innerHeight camera.aspect = width / height camera.updateProjectionMatrix() renderer.setSize(window.innerWidth, window.innerHeight) renderer.render(scene, camera) }) // renderer const renderer = new THREE.WebGL1Renderer() renderer.setSize(width, height) renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)) // animation function animate() { requestAnimationFrame(animate) renderer.render(scene, camera) } // rendering the scene const container = document.querySelector(”#threejs-container”) container.append(renderer.domElement) renderer.render(scene, camera) animate() </script> </body> </html> Output Print Page Previous Next Advertisements ”;

Three.js – Animations

Three.js – Animations ”; Previous Next Animations give life to our websites, as you can see that most of the examples use animations.Let”s see how to add basic animations to our Three.js web application. If you want to add animations to your Three.js scene, you”ll need to render the scene multiple times. To do that, you should use the standard HTML5 requestAnimationFrame functionality. function animate() { // schedule multiple rendering requestAnimationFrame(animate) renderer.render(scene, camera) } The above code executes the argument passes to requestAnimationFrame, animate function, at regular intervals, and also renders the scene multiple times (every 60ms). You now have your animation loop, so any changes made to your model, camera, or other objects in the scene can now be done from within the animate function. Let”s create a simple rotating animation. function animate() { requestAnimationFrame(animate) // rotating the cube cube.rotation.x += 0.005 cube.rotation.y += 0.01 renderer.render(scene, camera) } The above code creates a rotating cube. Every time the animate renders, the cube rotates by the specified values, which repeats as an infinite loop. You can also add animation to any other element in the scene. Check out this example and play around the scene exploring different animations. You can also use different animation libraries like Tween.js, Greensock, to create professional animations using Three.js. In the following section, let”s use tween.js to add animations to our 3D objects Using Twee.js in the Three.js project First things first, you should include the library in your project. Add a script tag or install from npm. <script src=”path/to/tween.js”></script> To use this library, we need to first create an instance of a TWEEN.Tween object. const initial = { x: 0, y: 1.25, z: 0, rot: 0 } const final = { x: 5, y: 15, z: -10, rot: 2 * Math.PI } const tween = new TWEEN.Tween(initial) It creates a TWEEN.Tween instance. We can use this instance to move the provided properties from the initial value to the final value. tween.to(final) With to function, we tell the tween object that we want to change the initial values to final values slowly. So, we vary the x property from 0 to 5. The second parameter, which is 5000, defines how many milliseconds this change should take. You can also choose how the value changes over time. For instance, you can use a linear easing function. It changes the values at a constant rate, which starts with small changes and quickly increases. Many more easing functions are predefined in TWEEN. tween.easing(TWEEN.Easing.Elastic.InOut) To make the 3D object animate, we need to be notified at every change. This is done with onUpdate(). If you want to be notified at the end of the tween, use onComplete(). tween.onUpdate(function () { cube.position.set(this.x, this.y, this.z) cube.rotation.set(this.rot, this.rot, this.rot) }) There are several other settings you can use on the tween object to control how the animation behaves. In this case, we tell the tween object to repeat its animation indefinitely and use a yo-yo effect that reverses the animation. tween.repeat(Infinity) tween.yoyo(true) Finally, we can start the tween object by calling the start function. tween.start() At this point, nothing happens. You have to update the tween so that it is updated whenever the text the scene renders. You can call it in the animate function. function animate() { requestAminationFrame(animate) TWEEN.update() } Now, you can see the effect. Similarly, you can use any animation library with Three.js. Print Page Previous Next Advertisements ”;

Three.js – Geometries

Three.js – Geometries ”; Previous Next Geometries are used to create and define shapes in Three.js. Three.js has many types of built-in geometries, both 2D and 3D. In this chapter, we”ll discuss basic built-in geometries. We’ll first look at the 2D geometries, and after that, we’ll explore all the basic 3D geometries that are available. Sr.No Geometrys & Description 1 Plane Geometry The THREE.PlaneGeometry creates a simple 2D rectangle. 2 Circle Geometry The THREE.CircleGeometry creates a simple 2D circle. 3 Ring Geometry The THREE.RingGeometry creates a D disc with a hole in the center. 4 Box Geometry The THREE.BoxGeometry creates a simple 3D box with specified dimensions. 5 Sphere Geometry The THREE.SphereGeometry creates 3D sphere geometries. 6 Cylinder Geometry To create a cylinder in Three.js, you can use the Three.CylinderGeometry. 7 Cone Geometry You can use THREE.ConeGeometry to create a cone. It is very similar to CylinderGeometry, except it only allows you to set the radius instead of radiusTop and radiusBottom. 8 Torus Geometry Torus is a tube-like shape that looks like a donut. You can use THREE.TorusGeometry to create a torus in Three.js. 9 TorusKnot Geometry A torus knot is a special kind of knot that looks like a tube that winds around itself a couple of times. 10 Polyhedron Geometry A polyhedron is a geometry that has only flat faces and straight edges. Learn more about geometries here Print Page Previous Next Advertisements ”;

Three.js – Loading 3D Models

Three.js – Loading 3D Models ”; Previous Next 3D models are available in many formats. You can import most of the models into Three.js and work with them quickly. Some formats are difficult to work with, inefficient for real-time experiences, or simply not fully supported by Three.js at this time. Let”s discuss some of the standard formats and how to load them into the Three.js file. Note − Only a few format loaders are built-in in Three.js. For loading other format models, you need to include their JavaScript files. You can find all the different loaders in the Three.js repo in the three/examples/jsm/loaders directory. For loading any model, we use these simple three steps − Include [NameOfFormat]Loader.js in your web page. Use [NameOfFormat]Loader.load() to load a URL. Check what the response format for the callback function looks like and render the result. OBJ Model Loader The OBJ file defines the geometry of the material in the form of text. Many other 3D Model software can create models in OBJ format. In Threejs, when importing an OBJ, the default material is a white MeshPhongMaterial. You need at least one light in your scene. You can use OBJLoader to load the models in OBJ format. To use OBJLoader in your Three.js project, you need to add the OBJLoader JavaScript file. <script type=”text/javascript” src=”../scripts/OBJLoader.js”></script> Then, you can load the model just like you loaded the texture using .load method. const loader = new THREE.OBJLoader() loader.load(”path/to/your/.obj file”, (object) => { scene.add(object) }) In this code, we use OBJLoader to load the model from a URL. Once the model is loaded, the callback we provide is called, and we can customize the loaded mesh if you want. MTL Model Loader OBJ and MTL are companion formats and often used together. The MTL file defines the materials used for the geometry in OBJ files. The MTL is also in a text-based format. <script type=”text/javascript” src=”../scripts/MTLLoader.js”></script> We”ll use MTLLoader and OBJLoader together in this code snippet. const mtlLoader = new THREE.MTLLoader() mtlLoader.load(”/path/to/your/.mtl file”, (materials) => { materials.preload() // loading geometry const objLoader = new THREE.OBJLoader() objLoader.setMaterials(materials) objLoader.load(”path/to/your/.obj file”, (object) => { mesh = object scene.add(mesh) }) }) It loads the materials first. Then we set the materials of the OBJ file to load as the loaded material and then load the OBJ file. It creates the mesh we needed to render an object to the scene, customizing the mesh or material just like those in the Three.js projects. GLTF Model Loader A glTF file may contain one or more scenes, meshes, materials, textures, skins, skeletons, morph targets, animations, lights, and cameras. It is the recommended format by official Three.js.Both.GLB and .GLTF versions of the format are well-supported by Three.js. Because glTF focuses on runtime asset delivery, it is compact to transmit and fast to load. <script src=”../scripts/GLTFLoader.js”></script> Using the GLTFLoader object, you can import either JSON (.gltf) or binary (.glb) format. const loader = new THREE.GLTFLoader() // loading model loader.load(”path/to/model.glb”, (gltf) => { scene.add(gltf.scene) }) The scene of the imported glTF model is added to our Three.js project. The loaded model may contain two scenes; you can specify the scene you want to import. DRACO Loader The DRACOLoader is used to load geometry (.drc format files) compressed with the Draco library. Draco is an open-source library for compressing and decompressing 3D meshes and point clouds. glTF files can also be compressed using the DRACO library, and they can also be loaded using the glTFLoader. We can configure the glTFLoader to use the DRACOLoader to decompress the file in such cases <script src=”../scripts/GLTFLoader.js”></script> <script src=”../scripts/DRACOLoader.js”></script> Like any other model, you can easily load the .drc files using DRACOLoader. And then, you can add Material to the geometry loaded and render the Mesh to the scene. const loader = new THREE.DRACOLoader() loader.setDecoderPath(”/scripts/draco/”) // Load a Draco geometry loader.load(”path/to/your/.drc file”, (geometry) => { const material = new THREE.MeshStandardMaterial({ color: 0xffffff }) const mesh = new THREE.Mesh(geometry, material) scene.add(mesh) }) This code snippet is used when you want to import glTF file format that has geometry compressed using Draco library. const dracoLoader = new THREE.DRACOLoader() dracoLoader.setDecoderPath(”/scripts/draco/”) dracoLoader.setDecoderConfig({ type: ”js” }) // loading glTF model that uses draco library const loader = new THREE.GLTFLoader() loader.setDRACOLoader(dracoLoader) loader.load(”models/monkey_compressed.glb”, (gltf) => { scene.add(gltf.scene) }) STL Model Loader The STL model format is widely used for rapid prototyping, 3D printing, and computer-aided manufacturing. STL files describe only the surface geometry of a 3D object without any representation of color, texture, or other common 3d modeling attributes. You can add them to the callback function. <script src=”../scripts/STLLoader.js”></script> We use the geometry from the .stl file and add material to it before adding it to the scene. const material = new THREE.MeshPhysicalMaterial({ color: 0xaaaaaa }) const loader = new THREE.STLLoader() loader.load(”path/to/your/.stl file”, (geometry) => { const mesh = new THREE.Mesh(geometry, material) scene.add(mesh) }) There are many other formats you can load into your Three.js project. The above mentioned are the standard formats. The Loader files are well-documented and easy to use. Troubleshooting If you cannot load your model correctly or it is distorted, discolored, or missing entirely. These are some troubleshooting steps mentioned in official Three.js site − Check the JavaScript console for errors, and make sure you”ve used an onError callback when calling .load() to log the result. View the model in another application. For glTF, drag-and-drop viewers are available for Three.js and Babylon.js. If the model appears correctly in one or more applications, file a bug against Three.js. If the model cannot be shown in any application, You should file a bug with the application used to create the model. Try

Three.js – Introduction

Three.js – Introduction ”; Previous Next All modern browsers became more powerful and more accessible directly using JavaScript. They have adopted WebGL (Web Graphics Library), a JavaScript API, which allows you to render highperformance interactive 3D and 2D graphics within any compatible web browser using the capabilities of the GPU (Graphics Processing Unit). But WebGL is a very low-level system that only draws basic objects like point, square, and line. However, programming WebGL directly from JavaScript is a very complex and verbose process. You need to know the inner details of WebGL and learn a complex shader language to get the most out of WebGL. Here comes Three.js to make your life easy. What is Three.js? Three.js is an open-source, lightweight, cross-browser, general-purpose JavaScript library. Three.js uses WebGL behind the scenes, so you can use it to render Graphics on an HTML <canvas> element in the browser. Since Three.js uses JavaScript, you can interact with other web page elements, add animations and interactions, and even create a game with some logic. Why use Three.js? The following features make Three.js an excellent library to use. You can create complex 3D graphics by just using JavaScript. You can create Virtual Reality (VR) and Augmented Reality (AR) scenes inside the browser. Since it uses WebGL, it has cross-browser support. Many browsers support it. You can add various materials, textures and animate 3D objects. You can also load and work on objects from other 3D modeling software. With a couple of lines of JavaScript and simple logic, you can create anything, from highperformance interactive 3D models to photorealistic real-time scenes. These are some excellent websites created using Three.js− Moments of happiness Garden Eight Interland Under Neon Lights You can find many other examples on the official website of three.js Browser Support All modern browsers on desktop, as well as on mobile, currently support WebGL. The only browser where you have to take care of is the mobile Opera Mini browser. For IE 10 and older,there is the IEWebGL plugin, which you can get from https://github.com/iewebgl/iewebgl./ You can find detailed information about the WebGL browser support here. Once you understand what Three.js is, you can continue to the next chapter about setting up a project to start working with Three.js. Print Page Previous Next Advertisements ”;

Three.js – Debug and Stats

Three.js – Debug & Stats ”; Previous Next Using Dat.GUI It is hard to keep experimenting with the values of variables, like the cube’s position. In that case, suppose until you get something you like. It”s a kind of slow and overwhelming process. Luckily, there is already a good solution available that integrates great with Three.js, dat.GUI. It allows you to create a fundamental user interface component that can change variables in your code. Installation To use dat.GUI in your project, download it here and add the <script> tag to the HTML file. <script type=”text/javascript” src=”path/to/dat.gui.min.js”></script> Or you can use CDN, add the following <script> tag inside your HTML. <script src=”https://cdnjs.cloudflare.com/ajax/libs/dat-gui/0.7.7/dat.gui.js”></script> If you are using Three.js in a node app, install the npm package – dat.GUI and import it into your JavaScript file. npm install dat.gui OR yarn add dat.gui import * as dat from ”dat.gui” Usage First, you should initialize the object itself. It creates a widget and displays it on the screen top rightcorner. const gui = new dat.GUI() Then, you can add the parameter you want to control and the variable. For example, the following code is to control the y position of the cube. gui.add(cube.position, ”y”) Example Try adding other position variables. Refer to this working code example. cube.html Live Demo <!DOCTYPE html> <html lang=”en”> <head> <meta charset=”UTF-8″ /> <meta http-equiv=”X-UA-Compatible” content=”ie=edge” /> <meta name=”viewport” content=”width=device-width, initial-scale=1.0″ /> <title>Three.js – Position GUI</title> <style> * { margin: 0; padding: 0; box-sizing: border-box; font-family: -applesystem, BlinkMacSystemFont, ”Segoe UI”, Roboto, Oxygen, Ubuntu, Cantarell, ”Open Sans”, ”Helvetica Neue”, sans-serif; } html, body { height: 100vh; width: 100vw; } #threejs-container { position: block; width: 100%; height: 100%; } </style> <script src=”https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js”></script> <script src=”https://cdnjs.cloudflare.com/ajax/libs/dat-gui/0.7.7/dat.gui.js”></script> </head> <body> <div id=”threejs-container”></div> <script type=”module”> // Adding UI to debug and experimenting different values // UI const gui = new dat.GUI() // sizes let width = window.innerWidth let height = window.innerHeight // scene const scene = new THREE.Scene() scene.background = new THREE.Color(0x262626) // camera const camera = new THREE.PerspectiveCamera(45, width / height, 0.1, 100) camera.position.set(0, 0, 10) // cube const geometry = new THREE.BoxGeometry(2, 2, 2) const material = new THREE.MeshBasicMaterial({ color: 0xffffff, wireframe: true }) gui.add(material, ”wireframe”) const cube = new THREE.Mesh(geometry, material) scene.add(cube) gui.add(cube.position, ”x”) gui.add(cube.position, ”y”) gui.add(cube.position, ”z”) // responsiveness window.addEventListener(”resize”, () => { width = window.innerWidth height = window.innerHeight camera.aspect = width / height camera.updateProjectionMatrix() renderer.setSize(window.innerWidth, window.innerHeight) renderer.render(scene, camera) }) // renderer const renderer = new THREE.WebGL1Renderer() renderer.setSize(width, height) renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)) // animation function animate() { requestAnimationFrame(animate) cube.rotation.x += 0.005 cube.rotation.y += 0.01 renderer.render(scene, camera) } // rendering the scene const container = document.querySelector(”#threejs-container”) container.append(renderer.domElement) renderer.render(scene, camera) animate() </script> </body> </html> Output You can customize the label displayed using the name attribute. To change the label on the variable line, use .name(“your label”). gui.add(cube.position, ”y”).name(”cube-y”) You can set up min/max limits and steps for getting the slider. The following line allow values from 1 to 10, increasing the value by 1 at a time. gui.add(cube.position, ”y”).min(1).max(10).step(1) // or gui.add(cube.position, ”y”, 1, 10, 1) If there are many variables with the same name, you may find it difficult to differentiate among them. In that case, you can add folders for every object. All the variables related to an object be in one folder. // creating a folder const cube1 = gui.addFolder(”Cube 1”) cube1.add(redCube.position, ”y”).min(1).max(10).step(1) cube1.add(redCube.position, ”x”).min(1).max(10).step(1) cube1.add(redCube.position, ”z”).min(1).max(10).step(1) // another folder const cube2 = gui.addFolder(”Cube 2”) cube2.add(greenCube.position, ”y”).min(1).max(10).step(1) cube2.add(greenCube.position, ”x”).min(1).max(10).step(1) cube2.add(greenCube.position, ”z”).min(1).max(10).step(1) Example Now, check the following example. gui-folders.html Live Demo <!DOCTYPE html> <html lang=”en”> <head> <meta charset=”UTF-8″ /> <meta http-equiv=”X-UA-Compatible” content=”ie=edge” /> <meta name=”viewport” content=”width=device-width, initial-scale=1.0″ /> <title>Three.js – More variables</title> <style> * { margin: 0; padding: 0; box-sizing: border-box; font-family: -applesystem, BlinkMacSystemFont, ”Segoe UI”, Roboto, Oxygen, Ubuntu, Cantarell, ”Open Sans”, ”Helvetica Neue”, sans-serif; } html, body { height: 100vh; width: 100vw; } #threejs-container { position: block; width: 100%; height: 100%; } </style> <script src=”https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js”></script> <script src=”https://cdnjs.cloudflare.com/ajax/libs/dat-gui/0.7.7/dat.gui.js”></script> </head> <body> <div id=”threejs-container”></div> <script type=”module”> // Adding folders to distinguish between variables // controls const gui = new dat.GUI() // sizes let width = window.innerWidth let height = window.innerHeight // scene const scene = new THREE.Scene() scene.background = new THREE.Color(0x262626) // camera const camera = new THREE.PerspectiveCamera(45, width / height, 0.1, 100) camera.position.set(0, 0, 10) const camFolder = gui.addFolder(”Camera”) camFolder.add(camera.position, ”z”).min(10).max(60).step(10) // cube const geometry = new THREE.BoxGeometry(2, 2, 2) const material = new THREE.MeshBasicMaterial({ color: 0xffffff, wireframe: true }) const cubeColor = { color: 0xffffff } const materialFolder = gui.addFolder(”Material”) materialFolder.add(material, ”wireframe”) materialFolder.addColor(cubeColor, ”color”).onChange(() => { // callback material.color.set(cubeColor.color) }) materialFolder.open() const cube = new THREE.Mesh(geometry, material) scene.add(cube) const cubeFolder = gui.addFolder(”Cube”) // for position const posFolder = cubeFolder.addFolder(”position”) posFolder.add(cube.position, ”x”, 0, 5, 0.1) posFolder.add(cube.position, ”y”, 0, 5, 0.1) posFolder.add(cube.position, ”z”, 0, 5, 0.1) posFolder.open() // for scale const scaleFolder = cubeFolder.addFolder(”Scale”) scaleFolder.add(cube.scale, ”x”, 0, 5, 0.1).name(”Width”) scaleFolder.add(cube.scale, ”y”, 0, 5, 0.1).name(”Height”) scaleFolder.add(cube.scale, ”z”, 0, 5, 0.1).name(”Depth”) scaleFolder.open() cubeFolder.open() // responsiveness window.addEventListener(”resize”, () => { width = window.innerWidth height = window.innerHeight camera.aspect = width / height camera.updateProjectionMatrix() renderer.setSize(window.innerWidth, window.innerHeight) renderer.render(scene, camera) }) // renderer const renderer = new THREE.WebGL1Renderer() renderer.setSize(width, height) renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)) // animation function animate() { requestAnimationFrame(animate) cube.rotation.x += 0.005 cube.rotation.y += 0.01 renderer.render(scene, camera) } // rendering the scene const container = document.querySelector(”#threejs-container”) container.append(renderer.domElement) renderer.render(scene, camera) animate() </script> </body> </html> Output You can also add some callback functions. onChange is triggered once the value is changed. gui.add(cube.position, ”y”).onChange(function () { // refresh based on the new value of y console.log(cube.position.y) }) Let”s see another example of changing color using dat.gui and callbacks. // parameter const cubeColor = { color: 0xff0000, } gui.addColor(cubeColor, ”color”).onChange(() => { // callback cube.color.set(cubeColor.color) }) The above callback onChange notifies Three.js to

Three.js – Useful Resources

Three.js – Useful Resources ”; Previous Next Three.js is an open-source JavaScript library that you can use to create dynamic and interactive websites with 2D and 3D graphics. With Three.js, you can render 3D graphics directly inside the browser. You can do fantastic stuff using Three.js by adding animations or logic and even turning your website into a game. Ricardo Cabello (or mrdoob in GitHub) released Three.js in 2010 and maintained a great open-source community. Useful Links on Three.js Three.js Wiki − Wikipedia Reference for Three.js. Three.js − Official website of Three.js. Useful Books on Three.js To enlist your site on this page, please drop an email to [email protected] Print Page Previous Next Advertisements ”;

Three.js – Libraries and Plugins

Three.js – Libraries and Plugins ”; Previous Next Official three.js examples are maintained as part of the three.js repository and always use the latest version of three.js. Listed here are externally developed compatible libraries and plugins for three.js Physics oimo.js enable3d ammo.js cannon-es cannon.js Postprocessing In addition to the Official three.js postprocessing effects, support for some additional effects and frameworks are available through external libraries. postprocessing Intersection and Raycasting Performance three-mesh-bvh File Formats In addition to the official three.js loaders, support for some additional formats is available through external libraries. urdf-loader 3d-tiles-renderer-js Webworker OBJloader IFC.js 3D Text and Layout troika-three-text three-mesh-ui Particle Systems three-nebula Inverse Kinematics THREE.IK fullik Game AI Yuka three-path-finding Wrappers and Frameworks A-Frame react-three-fiber ECSY It is the list maintained by the Three.js official community. Apart from these, there are many other libraries and plugins to add beautiful effects easier. Print Page Previous Next Advertisements ”;

Three.js – Materials

Three.js – Materials ”; Previous Next Material is like the skin of the object. It defines the outer appearance of the geometry. Three.js provides many materials to work. We should choose the type of material according to our needs. In this chapter, we”ll discuss the most commonly used materials in Three.js. Sr.No Materials & Description 1 MeshBasicMateria It is the very basic material in Three.js. 2 MeshDepthMaterial It uses the distance from the camera to determine how to color your mesh in a greyscale. 3 MeshNormalMaterial This material uses the magnitude of the x/y/z values of the faces’ normal vectors to calculate and set the red/green/blue values of the colors displayed on the face. 4 MeshLambertMaterial You can use this material to create dull-looking, non-shiny surfaces. 5 MeshPhongMaterial This material is similar to MeshLambertMaterial but can create more shiny surfaces. 6 MeshStandardMaterial It is similar but gives a more accurate and realistic looking result than the MeshLambertMaterial or MeshPhongMaterial. Instead of shininess, it has two properties: roughness and metalness. 7 MeshPhysicalMaterial It is pretty similar to MeshStandardMaterial. You can control the reflectivity of the material. 8 Using Multiple Materials Until now, while creating a Mesh, you added a single material to it. Print Page Previous Next Advertisements ”;