首页 > 解决方案 > 文本的 A-Frame 设置属性

问题描述

我正在尝试创建一个具有以下属性的文本实体,这样我就不必在每次使用文本时都指定这些细节

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

但我真的不明白“模式”和“AFRAME.registerComponent”是如何工作的。有人可以帮忙吗?

标签: aframe

解决方案


您可能对mixins感兴趣,这是创建可重用模板的另一种形式:

<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>

在您的情况下,它可能是text具有所有常见属性的简单混合:

<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>)只是说“我希望在将组件附加到实体<body>时拥有该功能”的一种形式。<name>

架构只是组件属性的声明。尝试遵循文档并编写您自己的组件,并在其行为异常时随时发布问题。


推荐阅读