Search code examples
aframewebvr

Fixed text position in A-Frame


I am trying to add fixed text in a-frame. I can add a a-text tag like this:

<a-camera wasd-controls-enabled="true" position="0 1 0" look-controls>
  <a-text position="0 0 -1" value="Test" color="#fff"></a-text>
</a-camera>

But this method does not make the text fixed to the side of the screen so the text will overflow when I change the screen size. Is this even possible?


Solution

  • It's generally best practice to add the text to the scene rather than to the camera. This gives the user the option to look in either direction so they can see everything.

    https://aframe.io/docs/0.8.0/components/camera.html#fixing-entities-to-the-camera

    If you still decide to anchor the text to the camera, the simple solution would be to make sure that the text is at a distance great enough that all of it can be seen comfortably at the smallest screen size (vertical phone orientation, etc.).

    A more complex solution would be to change the size of the <a-text> primitive (or containing entity using the text component) on the window.resize event, and adjusting the text container accordingly. This can be done by creating a custom component.

    Here is a rudimentary example:

    AFRAME.registerComponent('resize-text', {
    
      init: function() {
    
        var self = this;
    
        window.addEventListener('resize', function(e) {
    
          var height = window.innerHeight;
          var width = window.innerWidth;
    
          // console.log('resized!', height, width);
    
          self.el.setAttribute('width', ( width / 100 ));
    
        });
    
      }
    
    });
    

    And here is a demo of that code in action: https://codepen.io/dansinni/pen/pVJmQg

    Resize the window or drag the center divider and you will see that the text size changes.

    Hope this helps.