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

Add a startup method to Linux (service/script)

Configuration file that needs to be loaded when t...

Define your own ajax function using JavaScript

Since the network requests initiated by native js...

Introduction to the use of em in elastic layout in CSS3: How many pixels is 1em?

I have been using CSS for a long time, but I have...

Share 13 excellent web wireframe design and production tools

When you start working on a project, it’s importa...

In-depth explanation of Mysql deadlock viewing and deadlock removal

Preface I encountered a Mysql deadlock problem so...

A brief comparison of Props in React

Table of contents Props comparison of class compo...

Chinese and English font name comparison table (including Founder and Arphic)

In CSS files, we often see some font names become...

Solutions to problems using addRoutes in Vue projects

Table of contents Preface 1. 404 Page 1. Causes 2...

How to use HTML+CSS to create TG-vision homepage

This time we use HTML+CSS layout to make a prelim...

js to implement file upload style details

Table of contents 1. Overview 2. Parameters for c...

Analysis of MySQL lock wait and deadlock problems

Table of contents Preface: 1. Understand lock wai...

Detailed explanation of Vue filter implementation and application scenarios

1. Brief Introduction Vue.js allows you to define...

Solution to 404 Problem of Tomcat Installation in Docker

Find the containerID of tomcat and enter the toma...

jQuery uses the canvas tag to draw the verification code

The <canvas> element is designed for client...