You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决Angular项目中A-Frame+AR.js(Marker-based AR)的报错?

AR.js集成Angular项目报错排查与解决

问题背景

已在Angular项目中搭建基于A-Frame的Marker-based AR方案:

  • 通过NPM安装A-Frame 1.3.0,在pollyfills.ts中导入import aframe
  • 下载aframe-ar.js存为本地资源,在ngOnInit中用const ar= require('../../assets/ar_aframe.js');加载
  • 摄像头可正常启动、标记物能被识别,但控制台持续出现AR.js相关报错,更换旧版本AR.js无效

页面代码

<a-scene arjs="sourceType: webcam; detectionMode: mono_and_matrix; matrixCodeType: 3x3;" renderer="precision: medium;"
    vr-mode-ui="enabled: false" cursor="fuse: true;rayOrigin: mouse">
    <a-entity camera raycaster="objects: .clickable">
      <a-marker type="barcode" value="1" size="0.7">
        <a-box  position="0 0 0"
          material="opacity: 0.9; side: double;color:white;" class="clickable" width="2" height="2" depth="2"
          (click)="test($event,1)" geometry="primitive: box" aabb-collider>
        </a-box>
      </a-marker>
    </a-entity>
  </a-scene>

报错信息

类型错误

ERROR TypeError: Cannot read properties of undefined (reading 'addEventListener')
    at NewSystem.init (ar_aframe.js:1:1663386)
    at module.exports.System (aframe-master.js:28677:8)
    at new NewSystem (aframe-master.js:28775:12)
    at AScene.initSystem (aframe-master.js:27229:26)
    at module.exports.registerSystem (aframe-master.js:28785:15)
    at ar_aframe.js:1:1660640
    at ar_aframe.js:1:1664865
    at ar_aframe.js:1:1664871
    at ar_aframe.js:1:81
    at 4572 (ar_aframe.js:1:289)

断言失败报错(重复3次)

ar_aframe.js:1 Assertion failed: console.assert
b   @   ar_aframe.js:1
(anonymous) @   ar_aframe.js:1

解决方案

  • 延迟AR.js加载时机:Angular的ngOnInit执行时DOM可能未完全渲染,AR.js初始化找不到目标元素导致事件监听报错。将加载逻辑移至ngAfterViewInit钩子:

    ngAfterViewInit(): void {
      require('../../assets/ar_aframe.js');
    }
    
  • 匹配版本兼容性:A-Frame 1.3.0需搭配兼容的AR.js版本,推荐使用AR.js 3.4.0(适配A-Frame 1.x全系列),版本不匹配会导致内部API调用异常。

  • 排查组件冲突:暂时移除a-scene中的cursor="fuse: true;rayOrigin: mouse"和a-entity上的raycaster="objects: .clickable"配置,确认报错是否由组件冲突引发,正常后再逐步恢复配置。

  • 确保A-Frame完全初始化后加载AR.js:通过监听A-Frame场景的loaded事件触发AR.js加载,避免初始化顺序问题:

    ngAfterViewInit(): void {
      const scene = document.querySelector('a-scene');
      scene?.addEventListener('loaded', () => {
        require('../../assets/ar_aframe.js');
      });
    }
    

内容的提问来源于stack exchange,提问作者Tempo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 19:22:39