getBoundingClientRect 不是 Angular 11 - Three.js 上的函数

getBoundingClientRect is not a function on Angular 11 - Three.js

我尝试了几次解决这个问题,但我一直没能找到解决办法,我希望有人能帮助我。 我试图在我的网页上提供有关图像大小的信息,以便稍后实现滚动,这是我的代码:

  ngAfterViewInit() {
    let images = [{...document.querySelectorAll('img')}];
    this.addImages(images);
  }

 addImages(images) {
    this.imageStore = images.map(img => {
      let bounds = img.getBoundingClientRect();
      console.log(bounds);

      let geometry = new THREE.PlaneBufferGeometry(bounds.width, bounds.height, 1, 1);
      let material = new THREE.MeshBasicMaterial({ color: 0xff0000 })
      let mesh = new THREE.Mesh(geometry, material)
      this.scene.add(mesh);

      return {
        img: img,
        mesh: mesh,
        top: bounds.top,
        left: bounds.left,
        width: bounds.width,
        height: bounds.height
      }
    })
  }

该代码应该 return 我的 HTML 页面上图像的大小,但我得到了错误

  ngAfterViewInit() {
    const images = Array.from(document.querySelectorAll('img'));

    const imgObj = images.map((img) => {
      const bounds = img.getBoundingClientRect();
      return {
        img,
        name: img.name,
        top: bounds.top,
        bottom: bounds.bottom,
        left: bounds.left,
        width: bounds.width,
        height: bounds.height,
      };
    });

    console.log('Applying...');
    console.log({ imgObj });
  }

https://stackblitz.com/edit/angular-ivy-yeu1hx?file=src/app/app.component.ts

我认为问题在于您需要等待 图像加载完毕。

如果你的图像在一个数组中(有些像)

  images=["https://picsum.photos/200/300?random=1",
          "https://picsum.photos/200/300?random=2"]

你在 *ngFor 中显示它,使用事件 (load)

<ng-container *ngFor="let img of images">
<img #mimg [src]="img" (load)="pushData(mimg)">
</ng-container>

  array:any[]=[]
  pushData(el:any)
  {
   this.array.push(el.getBoundingClientRect())
   if (this.array.length==this.images.length)
   {
       console.log("all images loaded")
       ..do something..
   }
  }

更新 因为我们不知道图片加载的顺序,我们可以强制传递索引

<ng-container *ngFor="let img of images;let i=index">
<img #mimg [src]="img" (load)="pushData(mimg,i)">
</ng-container>
  pushData(el:any,index:number)
  {
   this.array[index]={
     ...el.getBoundingClientRect(),
     img:el
   }
   if (!this.array.find(x=>!x))
   {
          console.log("all images loaded")
   }
  }