首页 > 解决方案 > getBoundingClientRect 不是 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
      }
    })
  }

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

标签: angulargetboundingclientrect

解决方案


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

如果您的图像在数组中(有些像)

  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")
   }
  }

推荐阅读