如何从图像onLoad中返回变量

问题描述 投票:0回答:1
  export class AttachmentComponent {
   imageWidth: number;
   imageHeight: number;
   ngOnInit() {
    this.imgSize(imagePath);
   }
   getImageSize(url) {
    const img = new Image();
    img.src = imgurl;
    img.onload = (event) => {
      const  loadedImage: any = event.currentTarget;
      const width = loadedImage.width;
      const height = loadedImage.height;
    }
   }
 }

[这里,我要使用在getImageSize中的onLoad内部计算的宽度和高度来填充类的'imageWidth'和'imageHeight'属性。帮助吗?

javascript angular asynchronous observable onload
1个回答
0
投票

如果我对您的问题的理解是正确的,您想将loadedImage.width的值分配给imageWidth属性,并用height赋值。

您可以通过引用this(它是AttachmentComponent实例)来做到这一点。

export class AttachmentComponent {
   imageWidth: number;
   imageHeight: number;
   ngOnInit() {
    this.imgSize(imagePath);
   }
   getImageSize(url) {
    const img = new Image();
    img.src = imgurl;
    img.onload = (event) => {
      const  loadedImage: any = event.currentTarget;
      // => here is what I've changed
      this.imageWidth = loadedImage.width;
      this.imageHeight = loadedImage.height;
    }
   }
 }
© www.soinside.com 2019 - 2024. All rights reserved.