Rendering text with three.js in the scene

I'm just starting out with three.js.

For my project, I need to create a 3D graphical website.

After doing some research on Google, I discovered that three.js is a great tool for manipulating WebGL with ease.

In the three.js documentation(),

TextGeometry is the API used for drawing text in the scene.

[src.js]

init = () => {
  window.addEventListener('resize', resizeWindow);
  var scene = new THREE.Scene();
  var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 10000);
  var controls = new THREE.OrbitControls( camera );
  controls.update();
  var renderer = new THREE.WebGLRenderer();

  renderer.setClearColor(0xdd3b56);
  renderer.setSize(window.innerWidth, window.innerHeight);
  // Set shadow
  renderer.shadowMap.enabled = true;
  // Show Axis
  var axes = new THREE.AxisHelper(5);
  scene.add(axes);

  // Text
  var loader = new THREE.FontLoader();
  loader.load( './helvetiker_regular.typeface.json', function ( font ) {
      var geometry = new THREE.TextGeometry( 'Hello three.js!', {
          font: font,
          size: 80,
          height: 5,
          curveSegments: 12,
          bevelEnabled: true,
          bevelThickness: 10,
          bevelSize: 8,
          bevelSegments: 5
      } );
  } );
  var textMaterial = new THREE.MeshPhongMaterial({color: 0xFE98A0});
  var text = new THREE.Mesh(geometry, textMaterial);
  text.position.x = 0;
  text.position.y = 10;
  text.position.z = 10;
  scene.add(text);

  // Light
  var spotLight = new THREE.SpotLight(0xFFFFFF);
  spotLight.position.set(-40, 60, 30);
  spotLight.castShadow = true;
  spotLight.shadow.mapSize.width = 5120;
  spotLight.shadow.mapSize.height = 5120;
  scene.add(spotLight);

  // Camera Setting
  camera.position.x = 0;
  camera.position.y = 30;
  camera.position.z = 30;
  camera.lookAt(scene.position);
  document.getElementById("threejs_scene").appendChild(renderer.domElement);

  renderScene();

  function renderScene() {
    requestAnimationFrame(renderScene);
    controls.update();
    renderer.render(scene, camera);
  }
}
window.onload = init();

[index.html]

<html>
<head>
  <script src="three.js"></script>
  <script src="OrbitControls.js"></script>
  <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
  <div id="threejs_scene"></div>
  <script src="src.js"></script>
</body>
</html>

When running my code, I encountered the error message:

[.WebGL-0x7fb612852000]RENDER WARNING: Render count or primcount is 0.
and
WebGL: too many errors, no more errors will be reported to the console for this context.
.

Upon researching, I discovered that this error occurs when Three.js is attempting to render an object that has not been created yet.

However, in my code, I have already defined the object.

  var textMaterial = new THREE.MeshPhongMaterial({color: 0xFE98A0});
  var text = new THREE.Mesh(geometry, textMaterial);
  text.position.x = 0;
  text.position.y = 10;
  text.position.z = 10;

How can I resolve this issue?

Ultimately, my goal is to display text in the scene.

Thank you.

Answer №1

window.onload = function(params) {

  /*
   * INITIALIZING THE VIRTUAL WORLD
   * 
   */

  // Set up the ratio
  var gWidth = window.innerWidth;
  var gHeight = window.innerHeight;
  var ratio = gWidth / gHeight;
  var borders = [40, 24]; // Define the position for the ball to move

  var light = new THREE.AmbientLight(0xffffff, 0.5);
  var light1 = new THREE.PointLight(0xffffff, 0.5);
  light1.position.set(0, 5, 0);
  light1.castShadow = true;

  // Set up the renderer
  var renderer = new THREE.WebGLRenderer();
  var camera = new THREE.PerspectiveCamera();
  camera.position.set(10, 10, 10);
  camera.lookAt(new THREE.Vector3(0, 0, 0));

  // Set properties for casting shadow
  renderer.shadowMap.enabled = true;
  renderer.shadowMap.type = THREE.PCFSoftShadowMap;

  renderer.setSize(gWidth, gHeight);
  document.body.appendChild(renderer.domElement);

  var scene = new THREE.Scene();
  scene.add(light);
  scene.add(light1);

  var ground = new THREE.Mesh(new THREE.BoxGeometry(10, 0.5, 10), new THREE.MeshLambertMaterial());
  ground.receiveShadow = true;
  scene.add(ground);
  var geometry;

  var loader = new THREE.FontLoader();
  var mesh;

  requestAnimationFrame(render);

  function render() {
    if (mesh) {
      mesh.rotation.y += 0.01;
      mesh.rotation.z += 0.007;
    }
    renderer.render(scene, camera);
    requestAnimationFrame(render);
  }

  loader.load('https://cdn.rawgit.com/mrdoob/three.js/master/examples/fonts/helvetiker_regular.typeface.json', function(font) {

    var geometry = new THREE.TextGeometry('Hello three.js!', {
      font: font,
      size: 80,
      height: 5,
      curveSegments: 12,
      bevelEnabled: true,
      bevelThickness: 10,
      bevelSize: 8,
      bevelSegments: 5
    });

    var material = new THREE.MeshLambertMaterial({
      color: 0xF3FFE2
    });
    mesh = new THREE.Mesh(geometry, material);
    mesh.position.set(0, 2, 0);
    mesh.scale.multiplyScalar(0.01);
    mesh.castShadow = true;
    scene.add(mesh);

    var canv = document.createElement('canvas');
    canv.width = canv.height = 256;
    var ctx = canv.getContext('2d');
    ctx.fillStyle = 'white';
    ctx.fillRect(0, 0, canv.width, canv.height);
    ctx.fillStyle = 'black';
    ctx.fillText("HERE IS SOME 2D TEXT", 20, 20);
    var tex = new THREE.Texture(canv);
    tex.needsUpdate = true;
    var mat = new THREE.MeshBasicMaterial({
      map: tex
    });
    var plane = new THREE.Mesh(new THREE.PlaneGeometry(10, 10), mat);
    scene.add(plane);
  });

}
body {
  padding: 0;
  margin: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/96/three.min.js"></script>
<html>

<head>

</head>

<body>
</body>

</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Avoid navigating through hidden tab indexes

Below is the HTML code that I am working with: <span tabindex="19"> </span> <span tabindex="20"> </span> <span tabindex="21"> </span> <span id="hidden" tabindex="22"> </span> <span tabindex="23"&g ...

What is the best way to access a scope variable within a directive in Angular?

I need to access a scope variable within a directive as a JavaScript variable. Here is the code snippet: app.controller("Home", ["$scope", function($scope) { ... $scope.nb_msg = data.length; ... }]); app.directive("myDiv", function() { // ...

Leveraging Ajax to fetch JQuery

Currently, I am utilizing Ajax to trigger a PHP file for processing upon form submission. The JQuery form validation mechanism evaluates the variables' values to determine whether to proceed with submitting the form or to return false while displaying ...

`The height attribute of the textarea element is not being accurately adjusted`

When I tried to match the width(178px) and height(178px) of my table to the width and height of a text area upon clicking a button, I encountered an issue. While setting the width works perfectly fine, the height is being set to only 17px. It seems like ...

Tips for concurrently and asynchronously executing multiple AJAX requests

I am working with a javascript object named Agendamento which includes the following key parts: const Agendamento = { // ... storeResultados: async function (consulta) { //... $.ajax({ type: 'POST', ...

Using a Firebase token repeatedly: simple steps to follow

I have integrated Firebase Web Notification using Firebase SDK. The implementation process involves two files: a) generate-token.js and b) firebase-messaging.sw.js To get access token, permission is requested by calling requestPermission function. Upon ...

After subscribing, my Angular template fails to refresh

Currently, I am facing an issue with my Angular 17 project where the data fetched from the API is not updating the template. This means that despite receiving the data, I am unable to display it on the page. The code snippet below shows the service compon ...

Moving Angularjs table rows to another tableMoving table row from one Angular

I need a solution for transferring rows from one table to another. Here are the two tables involved: First Table: <table> <tr ng-repeat="row in items"> <td>{{row.PRODUCTDESCRIPTION}}</td> <td><inpu ...

When onSucess is called within a Vue view, the metadata parameter returns undefined, whereas it works properly inside a

In my Vue component for Plaid Link, there is a function/action in my Vuex store called onSuccess. This function is supposed to call my backend API to exchange the public token for an access token and send some data about the link to the backend. However, I ...

Exploring the method to deactivate and verify a checkbox by searching within an array of values in my TypeScript file

I am working on a project where I have a select field with checkboxes. My goal is to disable and check the checkboxes based on values from a string array. I am using Angular in my .ts file. this.claimNames = any[]; <div class="row container"> ...

Keeping firebase auth while removing firestore from Vue project

I have recently made the switch from Firestore to MongoDB, and I am currently in the process of removing references to Firestore in my App.vue file. However, I am still utilizing Firebase authentication. Upon checking the console error message, I came acr ...

Having trouble with bootstrap carousel malfunctioning on Firefox browser?

I'm experiencing an issue with the carousel slider on my website. It seems to only be working in Chrome and not in Mozilla Firefox. You can view the live site at: Below is the code I have used for the carousel: <header id="myCarousel" class="car ...

Angular 6: Harnessing the Power of Subject

In my angular applications, I have been utilizing the Subject feature from the rxjs library to create an event emitter. However, upon migrating to Angular 6, I encountered the issue that this module is no longer available. Cannot find module 'rxjs/Su ...

Determine the percentage of clicks on an HTML5 canvas radial progress bar

Recently, I designed a circular progress bar displaying a specific percentage. However, I am facing a challenge in determining how to calculate the percentage when a user clicks on either the black or green part of the circle. Could you provide insight on ...

Avoid displaying the image when encountering a 404 error, but sometimes a broken image may still appear momentarily

Here is the code snippet I'm currently using: <img ng-show="json.user.picture" ng-src="{{json.user.picture}}" ng-error="json.user.picture = false"> When accessing an image from an external website without permission, a 404 error code is return ...

How can I use jQuery to access the parent node in an XML document?

I have been trying to extract the top-level 'label' attribute from the XML code below using jQuery, but I haven't had any luck so far. I have already converted it into a DOM object, but the results are not what I expected. Does anyone have a ...

The URL switches back and forth from "localhost:8100" to "localhost:8100/some-route" while displaying a blank white screen

After working on my ionic app without any issues, I restarted my computer only to find that when I tried to run the project again, I was met with a blank white screen on both the browser and device. Even when I reverted back to an earlier branch, the URL c ...

What is the best method to assign each key in an Object to the corresponding value in another Object?

Suppose I have an object called data: { first: 'Zaaac', last: 'Ezzell', title: 'Mrs', mail: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="83ece6f9f9e6efefb3c3f1e6e7e7eaf7ade ...

Trouble displaying MongoDB data on Meteor template

As I embarked on building my first app with Meteor, everything seemed to be going smoothly until I encountered an issue where a collection was no longer displaying in a template. Here is the code snippet: App.js Tasks = new Mongo.Collection("tasks"); i ...

Transforming a d3 line chart into a bar chart

Beginner in D3 seeking assistance. I have successfully created a line chart that meets my requirements. Below is the code I used, with some modifications, mostly inspired by this source: <!DOCTYPE html> <meta charset="utf-8"> <sty ...