简体   繁体   中英

Making dynamic text with Three.js and dat.gui

I want to make a dynamic render of user inputted text using three.js and dat.gui, so far i've made this to render out the text:

var displayGui = function(){
  var gui = new dat.GUI();
  var parameters = {
    message:"sample",
    spinVelocity: 0
  }
  //Adds Text controls
  var myText = gui.add(parameters, 'message').name('Text');
  myText.onChange(function () {
      //adds text
      var loader = new THREE.FontLoader();
      loader.load('fonts/OpenSansBold.json', function(font) {
          console.log(myText);
          var textGeo = new THREE.TextGeometry(myText, {
              font: font,
              size: 200,
              height: 50,
              curveSegments: 12,
              position: 3,
              bevelThickness: 2,
              bevelSize: 5,
              bevelEnabled: true,
          });

          var textMaterial = new THREE.MeshPhongMaterial({ color: 0xff0000 });

          var mesh = new THREE.Mesh(textGeo, textMaterial);
          mesh.position.set(100, 100, 100);
          scene.add(mesh);
      });
  });
  gui.add(parameters, 'spinVelocity').name('Spin');
  gui.open();

  };

However, as you can see on here , it just renders out a big red 3D text that says [object Object] , i have suspected that this may be because var myText is an object and not a string, so i tried to String(myText) however, it did not change much and it still did not work.

Is this not working because the text is not a string or is this because three.js is not recognizing the text inputted by the user on the dat.gui interface?

You should not be trying to load the font each time your dat.gui fires. Your code has a horrible performance problem, and it's likely that you would run out of memory after fiddling with the gui for a while.

My understanding is that this code creates a new instance of geometry each time you change the value in the gui, and never disposes of them. You're filling up your gpu with copies of this mesh.

Specific to your question, you're using datgui wrong:

console.log(myText); //logs the intance of a gui object (a JS object with methods and such)

change to:

console.log(parameters.message);

To fix the reloading issue, cache your font

var myFont
loader.load('fonts/OpenSansBold.json', function(font) {
   myFont = font
   //your gui is not ready until the font comes so, for example you could instantiate it here
   gui.add(...).onChange(function(){..})
})

Change line

myText.onChange(function () { 

to

myText.onChange(function (value) {

Then value will contain the new value of the input.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM