AFrame:触发markerFound监听器时获取marker ID

AFrame: Get the marker ID when markerFound listener is triggered

我有一个带有多个标记的 AR 场景,这些标记在激活时显示不同的 3d 模型。 像这样:

<a-scene embedded arjs>     
    <a-marker markerhandler preset="custom" type="pattern" url="Target1.patt" id="1">
        <a-image src="image1.jpg"></a-image>
    </a-marker>
    <a-marker markerhandler preset="custom" type="pattern" url="Target2.patt" id="2">
        <a-image src="image2.jpg"></a-image>
    </a-marker>
    <a-entity camera></a-entity>
</a-scene>

以及关联的脚本:

<script>
AFRAME.registerComponent('markerhandler', {
    init: function () {
      this.el.sceneEl.addEventListener('markerFound', (e) => {
          alert(this.id); //This should show the id ("1" or "2" in the example)
      })
    }
  });
</script>

如何识别触发了哪个目标并获取 ID? 我尝试了一切,但我快要疯了,感谢您的帮助。谢谢!

在这种情况下,this 指的是组件主体。根据上下文 this 将引用不同的上下文

AFRAME.registerComponent("foo", {
  init: function() {
    console.log("init", this) // this - components body
    this.el.addEventListener("loaded", function() {
      // this - the element which the listener is added to
      console.log("function callback", this)
    })
    this.el.addEventListener("loaded", evt => {
      // this - the components body, because of the arrow function
      console.log("lambda callback", this) 
    })
  }
})

也就是说 - 您正在寻找 this.el.id,因为您缺少元素参考。在下面的代码片段(底部日志)中查看:

<script src="https://aframe.io/releases/1.2.0/aframe.min.js"></script>
<script>
  AFRAME.registerComponent("foo", {
    init: function() {
      console.log("init. id: ", this.el.id)
      this.el.addEventListener("loaded", function() {
        console.log("function callback. id: ", this.id)
      })
      this.el.addEventListener("loaded", evt => console.log("arrow func. callback. id: ", this.el.id));
    }
  })
</script>
<a-scene>
  <a-box id="one" position="-1 0.5 -3" rotation="0 45 0" color="#4CC3D9" foo></a-box>
</a-scene>