Search code examples
aframe

A-Frame setting attributes for text


I'm trying to create a text entity with the following attributes so that I don't have to specify these details every time I use text

  text.setAttribute('color', #303030);
  text.setAttribute('width', 2);
  text.setAttribute('lineHeight', 60);
  text.setAttribute('align', 'center');
  text.setAttribute('baseline', 'top');
  text.setAttribute('wrapcount', 12);

but I don't really understand how 'schema' and 'AFRAME.registerComponent' work. can someone please help with how to do this?


Solution

  • You may be interested in mixins which is another form of creating a reusable template:

    <a-scene>
      <a-assets>
        <!-- define the template -->
        <a-mixin id="red" material="color: red"></a-mixin>
      </a-assets>
      <!-- use the template -->
      <a-box mixin="red"></a-box >
    </a-scene>
    

    In your case, it could be a simple text mixin with all common attributes:

    <script src="https://aframe.io/releases/1.2.0/aframe.min.js"></script>
    <script>
      AFRAME.registerComponent("text-creator", {
        init: function() {
          var messages = ["one", "two", "three"]
          for (var i = 0; i < 3; i++) {
            // create an <a-entity>
            var txt = document.createElement('a-entity')
            // use the mixin
            txt.setAttribute("mixin", "text")
            // set the text value
            txt.setAttribute("text", "value", messages[i])
            txt.setAttribute("position", -0.25 + i + " 2 -2")
            this.el.appendChild(txt)
          }
        }
      })
    </script>
    <a-scene text-creator>
      <a-assets>
        <a-mixin id="text" text="color: blue; width: 2, lineHeight: 60, align: center, baseline: top, wrapcount: 12"></a-mixin>
      </a-assets>
      <a-box position="-1 0.5 -3" rotation="0 45 0" color="#4CC3D9"></a-box>
      <a-sphere position="0 1.25 -5" radius="1.25" color="#EF2D5E"></a-sphere>
      <a-cylinder position="1 0.75 -3" radius="0.5" height="1.5" color="#FFC65D"></a-cylinder>
      <a-plane position="0 0 -4" rotation="-90 0 0" width="4" height="4" color="#7BC8A4"></a-plane>
    </a-scene>

    AFRAME.registerComponent(<name>, <body>) is just a form of saying "I want to have the <body> functionality when i attach the <name> component to an entity".

    The schema is just a declaration of the component's properites. Try to follow the docs and write your own component and feel free to post a question once it behaves in a weird way.