A-Frame:我在创建一个在平面上显示数字的按钮时遇到了问题

A-Frame: I am having trouble creating a button that displays a number on a plane

我是 A-frame 的初学者,试图在内部创建一个简单的计算器,但在将数字键制作成按钮时遇到了麻烦,按下按钮后会在显示屏上显示按下的数字。下面是我来自 html 和 js 的代码片段。 html包括显示屏幕和"number one"按钮。 js 包含 javascript 代码,该代码将在屏幕上显示填充数字。

//a frame   
<a-scene>
      <a-entity id ="display" position="0 2 -5" geometry="primitive: plane; height: 2; width: 5" material="color: teal"></a-entity>

      <a-entity id = "NumberOne" position = "-2 0.5 -5" geometry = "primitive: plane; height: 1; width: 1" material = "color:black" text="color: white; align: center; value: 1; width: 5"></a-entity>

    </a-scene>
//script
document.querySelector("#NumberOne").addEventListener('click', () => {
  display.innerHTML += 1;
});

其实A-Frame构建的是3D场景,文字是网格物体,HTML元素的内部HTML是无法改变的。 text您使用的是A-Frame中的一个组件。它有一些属性,例如字体,值。您应该更新这些属性以更改元素。

首先。我注册了一个新组件以在 HTML 元素 click 事件上添加一个事件侦听器。当您单击 NumberOne 元素时,我将获得此元素文本组件的值。并将其添加到 display 文本组件值。然后,用 setAttribute().

更新文本组件

这是我的脚本:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Add and display number</title>
    <meta name="description" content="Add and display number with A-Frame">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/aframe/0.5.0/aframe.min.js"></script> 
    
  </head>
  <body>
<script>
 AFRAME.registerComponent('add-number', {
    init: function () {
     this.display = document.querySelector("#display");
     this.el.addEventListener("click",this.onClick.bind(this));
    },
    onClick:function()
    {
      var num = parseInt(this.el.components.text.data.value);
      var displayValue = parseInt(this.display.components.text.data.value);
      var sum = displayValue+num;
      this.display.setAttribute("text","value",sum.toString());
    }
  });
</script>
<a-scene>
  <a-entity camera  look-controls
            position="0 1.764 0">
    <a-entity cursor="fuse: true; fuseTimeout: 500" position="0 0 -1"
              geometry="primitive: ring; radiusInner: 0.02; radiusOuter: 0.03;" material="color: #CCC; shader: flat;">
    </a-entity>
  </a-entity>

  <a-entity id ="display" position="0 2 -5" geometry="primitive: plane; height: 2; width: 5" material="color: teal" text="color: white; align: center; value: 1; width: 5"></a-entity>

  <a-entity id = "NumberOne" position = "-2 0.5 -5" geometry = "primitive: plane; height: 1; width: 1" material = "color:black" text="color: white; align: center; value: 1; width: 5" add-number></a-entity>

  <a-entity id="box" cursor-listener geometry="primitive: box" material="color: blue" position="-2 2.2 -1.5"></a-entity>

  <!-- Lighting -->
  <a-light type="ambient" color="#fff"></a-light>
</a-scene>


</body>
</html>