First experience of creating text with javascript Three.js

First experience of creating text with javascript Three.js

Effect

insert image description here

First, introduce the necessary components

import './build/three.js';
import './libs/js/controls/OrbitControls.js'
import { FontLoader } from './libs/jsm/loaders/FontLoader.js';
import { TextGeometry } from './libs/jsm/geometries/TextGeometry.js';

Then it is necessary to initialize the scene, renderer, camera, and controller

		var renderer, scene, camera, controls
		// Initialize the scene function initScene() {
            scene = new THREE.Scene();
            //Add smoke effect to the scene// Parameters: smoke color, smoke range near, smoke range far
            scene.fog = new THREE.Fog(0x000000, 0, 3000)
            // Add axes to the scene var axes = new THREE.AxesHelper(100)
            scene.add(axes)
        }
        // Initialize the renderer function initRenderer() {
            // Whether antialias is turned on renderer = new THREE.WebGLRenderer({ antialias: true })
            renderer.setSize(window.innerWidth, window.innerHeight)
            renderer.setClearColor(0xeeeeee)
            document.body.appendChild(renderer.domElement);
        }
        // Initialize the camera function initCamera() {
            camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000)
            camera.position.x = 50
            camera.position.y = 50
            camera.position.z = 50
        }
        // Initialize the controller function initControls() {
            controls = new THREE.OrbitControls(camera, renderer.domElement)
            controls.enableZoom = false; //Whether to enable zoom;
            controls.minPolarAngle = Math.PI / 2.5; //Limit the minimum rotation angle in the vertical direction to 0 degrees on the positive y-axis controls.maxPolarAngle = Math.PI / 2.5; //Limit the maximum rotation angle in the vertical direction to 0 degrees on the positive y-axis}

Initialize the light source

		// Initialize the light source function initLight() {
        // White light, light intensity 1
            var pointLight = new THREE.PointLight(0xffffff, 1);
            pointLight.position.set(0, 100, 100);
            scene.add(pointLight);
            var pointLight = new THREE.PointLight(0xffffff, 1);
            pointLight.position.set(0, 100, -100);
            scene.add(pointLight);
        }

Start creating text

First create the font loader

var loader = new FontLoader();

Load font library

After successfully loading the font library resource, the font library will be passed to the callback function

loader.load(src, callback)

The font library resources can select the desired ttf font file through typeface.json and convert it into a json file, and then create the font geometry in the callback function.

loader.load('./fonts/FZKaTong-M19S_Regular.json', function (response) {
               // Create text here})

Creating Text Geometry

				// Create text buffer geometry var textGeometry = new TextGeometry('狗托吴嘉豪', {
                	// Font type font: response,
                    // font size: 15,
                    // font thickness height: 1,
                    // The number of points on the text curve. The higher the number, the smoother the font curve. curveSegments: 12,
                    // Whether to turn on bevel (smooth transition of edges and corners)
                    bevelEnabled: false,
                    // The depth of the bevel on the text bevelThickness: 0.1,
                    // The extension distance between the bevel and the original text outline (bevel size)
                    bevelSize: 0.1,
                    // bevel segments number bevelSegments: 3
                })
				//Text material //Use material array var textMaterial = [
                    // The first item modifies the front and back of the text new THREE.MeshPhongMaterial( { color: 0x00ff00, flatShading: true } ), // front
                    // The second item modifies the text side (top and bottom)
					new THREE.MeshPhongMaterial( { color: 0x0000ff, flatShading: true } ) // side
                    // Phong mesh material can simulate shiny surfaces with specular highlights (such as painted wood)
				] 
				// Create text var text = new THREE.Mesh(textGeometry, textMaterial)

Calculate the bounding rectangle of the text geometry

We can imagine that the geometric body is stored in an invisible rectangular cube container, and the default position of this container is the origin, extending outward along the positive direction of the x-axis and z-axis, so that our text will not be in the center of the field of vision.
At this point, we can calculate the outer bounding rectangle of the geometry and set the position of the geometry to move half of its length in the opposite direction so that no matter how long the geometry becomes, it is always in the center of the field of view.

				// computeBoundingBox() calculates the outer bounding rectangle of the current geometry textGeometry.computeBoundingBox();
                // console.log(textGeometry.boundingBox); Check the vertex position of the outer bounding rectangle // Move the text position to the left by half the length of the text var centerOffset = -0.5*(textGeometry.boundingBox.max.x-textGeometry.boundingBox.min.x)
                text.position.x = centerOffset
                text.position.z = 0  
                scene.add(text);

Create mirrored text

				// Create a text mirror var mirror = new THREE.Mesh(textGeometry, textMaterial)
                // Flip 180 degrees mirror.rotation.x = Math.PI
                mirror.position.x = centerOffset
                mirror.position.y = -8
                scene.add(mirror)

Creating a semi-transparent plane

				// Create a text mirror var mirror = new THREE.Mesh(textGeometry, textMaterial)
                // Flip 180 degrees mirror.rotation.x = Math.PI
                mirror.position.x = centerOffset
                mirror.position.y = -8
                scene.add(mirror)

Rendering

		function render() {
            renderer.render(scene, camera);
            requestAnimationFrame(render)
        }
        function start() {
            initRenderer()
            initScene();
            initCamera();
            initControls()
            initLight()
            initText()
            render()
        }
        start()

About Text Constructor Parameters

When curveSegments is set lower, you can see that the text is not so smooth

// The number of points on the text curve, the higher the point, the smoother the curve curveSegments: 1,

insert image description here

When the bevel is turned on, you can observe that the edges of the font become rounded and no longer sharp.

// Whether to turn on bevel (smooth transition of edges and corners)
bevelEnabled: true,

insert image description here

Setting bevel parameters

// The depth of the bevel on the text bevelThickness: 0.1,
// The extension distance between the bevel and the original text outline (bevel size)
bevelSize: .1,
// bevel segments number bevelSegments: 3

Complete code

<script type="module">
        import './build/three.js';
        import './libs/js/controls/OrbitControls.js'
        import { FontLoader } from './libs/jsm/loaders/FontLoader.js';
        import { TextGeometry } from './libs/jsm/geometries/TextGeometry.js';
        var renderer, scene, camera, controls
        // Initialize the renderer function initRenderer() {
            // Whether antialias is turned on renderer = new THREE.WebGLRenderer({ antialias: true })
            renderer.setSize(window.innerWidth, window.innerHeight)
            renderer.setClearColor(0xeeeeee)
            document.body.appendChild(renderer.domElement);
        }
        // Initialize the scene function initScene() {
            scene = new THREE.Scene();
            //Add smoke effect to the scene// Parameters: smoke color, smoke range near, smoke range far
            scene.fog = new THREE.Fog(0x000000, 0, 3000)
            // Add axes to the scene var axes = new THREE.AxesHelper(100)
            scene.add(axes)
        }
        // Initialize the camera function initCamera() {
            camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000)
            camera.position.x = 50
            camera.position.y = 50
            camera.position.z = 50
        }
        // Initialize the controller function initControls() {
            controls = new THREE.OrbitControls(camera, renderer.domElement)
        }
        // Initialize the light source function initLight() {
            var pointLight = new THREE.PointLight(0xffffff, 1);
            pointLight.position.set(0, 100, 100);
            scene.add(pointLight);
            var pointLight = new THREE.PointLight(0xffffff, 1);
            pointLight.position.set(0, 100, -100);
            scene.add(pointLight);
        }
        function initText() {
            var loader = new FontLoader();
            loader.load('./fonts/FZKaTong-M19S_Regular.json', function (response) {
                // Create text geometry var textGeometry = new TextGeometry('狗托吴嘉豪', {
                    font: response,
                    // font size: 15,
                    // font thickness height: 4,
                    // The number of points on the text curve, the higher the point, the smoother the curve curveSegments: 12,
                    // Whether to turn on bevel (smooth transition of edges and corners)
                    bevelEnabled: true,
                    // The depth of the bevel on the text bevelThickness: 0.1,
                    // The extension distance between the bevel and the original text outline (bevel size)
                    bevelSize: .1,
                    // bevel segments number bevelSegments: 3
                })
                //Text material //Use material array var textMaterial = [
                    // The first item modifies the front and back of the text new THREE.MeshPhongMaterial( { color: 0x00ff00, flatShading: true } ), // front
                    // The second item modifies the text side (top and bottom)
					new THREE.MeshPhongMaterial( { color: 0x0000ff, flatShading: true } ) // side
                    // Phong mesh material can simulate shiny surfaces with specular highlights (such as painted wood)
				] 
                var text = new THREE.Mesh(textGeometry, textMaterial)
                // computeBoundingBox() calculates the bounding rectangle of the current geometry textGeometry.computeBoundingBox();
                // console.log(textGeometry.boundingBox);
                var centerOffset = -0.5*(textGeometry.boundingBox.max.x-textGeometry.boundingBox.min.x)
                text.position.x = centerOffset
                text.position.z = 0  
                scene.add(text);
                // Create a text mirror var mirror = new THREE.Mesh(textGeometry, textMaterial)
                mirror.rotation.x = Math.PI
                mirror.position.x = centerOffset
                mirror.position.y = -8
                scene.add(mirror)
                // Create a semi-transparent plane var plane = new THREE.Mesh(new THREE.PlaneBufferGeometry(200,200),new THREE.MeshBasicMaterial({color:0xffffff,opacity:.5,transparent:true}))
                plane.rotation.x = -Math.PI / 2
                plane.position.y = -3
                scene.add(plane)
            })
        }
        function render() {
            renderer.render(scene, camera);
            requestAnimationFrame(render)
        }
        function start() {
            initRenderer()
            initScene();
            initCamera();
            initControls()
            initLight()
            initText()
            render()
        }
        start()
    </script>

Summarize

This article ends here. I hope it can be helpful to you. I also hope that you can pay more attention to more content on 123WORDPRESS.COM!

You may also be interested in:
  • Three.js realizes Facebook Metaverse 3D dynamic logo effect
  • Detailed process of drawing three-dimensional arrow lines using three.js
  • Use three.js to achieve cool acid style 3D page effects
  • How to achieve 3D dynamic text effect with three.js
  • Three.js sample code for implementing dewdrop animation effect
  • Detailed explanation of the use and performance testing of multithreading in three.js

<<:  How to connect to MySQL database using Node-Red

>>:  Example code for mixing float and margin in CSS

Recommend

Vue directives v-html and v-text

Table of contents 1. v-text text rendering instru...

MySQL 5.7.17 installation and configuration tutorial under Linux (Ubuntu)

Preface I have installed MySQL 5.6 before. Three ...

Mobile browser Viewport parameters (web front-end design)

Mobile browsers place web pages in a virtual "...

Use the more, less, and cat commands in Linux to view file contents

In Linux, the commands cat, more, and less can al...

Deep understanding of JavaScript syntax and code structure

Table of contents Overview Functionality and read...

Analysis of the process of building a cluster environment with Apache and Tomcat

In fact, it is not difficult to build an Apache c...

CSS performance optimization - detailed explanation of will-change usage

will-change tells the browser what changes will h...

How to install MySQL 5.7 from source code in CentOS 7 environment

This article describes how to install MySQL 5.7 f...

Use of Vue3 pages, menus, and routes

Table of contents 1. Click on the menu to jump 1....

How to modify the group to which a user belongs in Linux

Modify the group to which a user belongs in Linux...

React.js framework Redux basic case detailed explanation

react.js framework Redux https://github.com/react...

Introduction to Kubernetes (k8s)

I had always wanted to learn Kubernetes because i...

Docker installs mysql and solves the Chinese garbled problem

Table of contents 1. Pull the mysql image 2. Chec...