简体   繁体   English

如何使用 Ionic 3 在 Android 上为 Image() 触发 onload 事件

[英]How to fire onload event for Image() on Android with Ionic 3

I'm trying to trigger function on "onload" event of Image() (HTMLImageElement) on Android with Ionic 3. It works with iOS but unfortunately doesn't work with Android.我正在尝试使用 Ionic 3 在 Android 上触发 Image() (HTMLImageElement) 的“onload”事件的函数。它适用于 iOS,但不幸的是不适用于 Android。

How can I trigger onload function on Android?如何在 Android 上触发onload功能? I do not use it with <img> or other tag, so I cannot fire it with <img (load)="functionHere()"> .我不将它与<img>或其他标签一起使用,所以我不能用<img (load)="functionHere()">触发它。

(I have seen some of the other "onload" questions on Stack Overflow, this is about a specific situation with Android/Ionic 3). (我在 Stack Overflow 上看到了其他一些“onload”问题,这是关于 Android/Ionic 3 的特定情况)。

Here is my example code:这是我的示例代码:

this.backgroundImageSource = new Image();
this.backgroundImageSource.src = this.image;


this.backgroundImageSource.onload = function() {
    // THIS PART DOESNT FIRE ON ANDROID
    console.log("ONLOAD TRIGGERED");
}

If the example code is used exactly as shown, then the issue could be with onload event handler being defined after the event could happen.如果示例代码完全按照所示使用,那么问题可能在于在事件发生后定义了onload事件处理程序。 You should define the event handler function before the event could occur.您应该在事件发生之前定义事件处理函数。

So onload must be handled before src attribute is set.所以必须在设置src属性之前处理onload Although, I'm not sure if the JS engine fixes this in any of its optimization steps.虽然,我不确定 JS 引擎是否在任何优化步骤中修复了这个问题。

this.backgroundImageSource = new Image();

//This has to be done before setting src
this.backgroundImageSource.onload = function() {
    console.log("ONLOAD TRIGGERED");
}

this.backgroundImageSource.src = this.image;

I had the same problem.我有同样的问题。

I discovered that the base64 did not include a header/descriptor and so for that reason it was not firing.我发现 base64 不包含标题/描述符,因此它没有触发。

I fixed this by appending a header in cases where one did not exist:我通过在不存在标题的情况下附加标题来解决此问题:

if (!base64Data.includes(',')) {
  // Detect if base64 image is missing header/descriptor
  console.log("Prepending descriptor to Base64 image string")
  base64Data = `data:image/jpeg;base64,${base64Data}`;
}

(The comma is used to separate the header from the body). (逗号用于将标题与正文分开)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM