Search code examples
angulargetboundingclientrect

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


I try several time to solve this issue but I have not been able to find a solution, I hope that someone could help me. I'm trying to provide information about the size of the images on my webpage to implement the scroll later, this is my code:

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

That code should return the sizes of the images on my HTML page, but I got the error


Solution

  •   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