首页 > 解决方案 > 图像的CSS网格 - 浏览器调整大小的响应问题

问题描述

所以我在 3x3 css 网格上总共绘制了 9张图像(我们的平台是 Angular 11)。每个图像都被传递到一个子组件中,并绘制到一个画布上。

在子组件触发之前,我在ngAfterViewInit () 中计算网格单元格的高度/宽度,然后将这些值传递给子组件。

ngAfterViewInit() {
// FIRST TIME WE GET THE HT/WD OF OUR GRID TILE.
this.tileHeight = this.tileElem.nativeElement.clientHeight;
this.tileWidth = this.tileElem.nativeElement.clientWidth; 

}

最初,此时获取网格单元格 div 的 ht/wd不是问题。

但是,在resize上,我想重新计算该网格单元格 div 的高度/宽度。但在某些情况下,这个 div 大小会一遍又一遍地报告相同的大小——无论我调整浏览器大小并在调整大小事件函数中设置断点。

两个具体场景:

  1. 最大化我的浏览器然后进入我的视图。图像被绘制到画布上,并且所有图像都在每个网格图块/单元格内正确缩放。将我的浏览器缩小一点,画布不会在每个网格图块内调整大小。图像都保持相同的大小 -不是预期的行为。

  2. 首先将我的浏览器缩小到屏幕最大值以下。进入我的网格视图,图像被适当地缩小以适合每个网格图块。上下调整浏览器大小,我可以看到画布调整大小以正确缩放我的图像。这是预期的行为

场景 1屏幕截图(从 max'd 浏览器开始,然后缩小尺寸。图像缩小):

浏览器最初是最大尺寸,然后是 DOWN 尺寸。 图像不缩放。

场景 2屏幕截图(开始浏览器尺寸缩小一点,上下调整大小。图像缩放正确):

当浏览器最初低于最大值时,图像会正确缩放。

在父组件中,获取网格 tile div 的宽度/高度:

export class myGridComponent implements AfterViewInit, OnInit, OnChanges { 

 @ViewChild('tileDiv', { static: false }) tileElem: ElementRef<HTMLElement>;
  @ViewChild('gridDiv', { static: false }) gridContainerDiv: ElementRef<HTMLElement>;
  tileHeight: number;
  tileWidth: number;
  gridHeight: number;
  
  @HostListener('window:resize', ['$event'])
  onResize(event: Event)
  {
    console.log(event.srcElement.innerHeight);
    this.tileHeight = THE_NEW_HEIGHT;
  }
    

ngAfterViewInit() {
    // FIRST TIME WE GET THE HT/WD OF OUR GRID TILE.
    this.tileHeight = this.tileElem.nativeElement.clientHeight;
    this.tileWidth = this.tileElem.nativeElement.clientWidth;
    this.gridHeight = this.gridContainerDiv.nativeElement.clientHeight;
  }
  
  
  }
<div
      *ngFor="let item of imagesItems; let index = index"
      #tileDiv
    >
        <!-- DRAW IMAGE TO TILE CANVAS -->
        <image-tile     
          [sourceImage]="item.image"          
          [height]="showFullscreenGrid ? gridHeight : tileHeight"
          [width]="tileWidth"
        ></image-tile>
        
</div>

标签: htmlcsshtml5-canvascss-grid

解决方案


推荐阅读