Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use onload event from Image in typescript?

Tags:

typescript

I want to get some info from an image that i load using new image() with typescript. I try this code:

width;
heigth;
init(){
    let image = new Image();
    image.src = "url";

    image.onload((event) => {
    this.width = event.width;
    this.heigth = event.heigth;
    })
}

But i get this error:

void' is not assignable to parameter of type 'Event'. Property 'bubbles' is missing in type '() => void'

I search examples on how to use this event but i can't find anything.

like image 404
Ray Orellana Avatar asked Nov 13 '17 14:11

Ray Orellana


People also ask

How do you write onload function in typescript?

onload = (event) => { // ... }; You will also find that the general Event type doesn't have width and height, so you may need to specialise the type for that too. Show activity on this post. What a neat solution!

What is IMG onload?

Description. The onload property of an Image object specifies an event handler function that is invoked when an image loads successfully. The initial value of this property is a function that contains the JavaScript statements specified by the onload attribute of the <img> tag that defined the Image object.

How do you add onload event to a div element?

The onload event can only be used on the document(body) itself, frames, images, and scripts. In other words, it can be attached to only body and/or each external resource. The div is not an external resource and it's loaded as part of the body, so the onload event doesn't apply there.

How do I use document onload?

Definition and Usage The onload event occurs when an object has been loaded. onload is most often used within the <body> element to execute a script once a web page has completely loaded all content (including images, script files, CSS files, etc.).


2 Answers

HTMLImageElement worked for me:

  image.onload = function (this: HTMLImageElement) {
  const height = this.height;
  const width = this.width;
  console.log('Image size ', [width, height])
};
like image 84
Alexander Poshtaruk Avatar answered Oct 11 '22 21:10

Alexander Poshtaruk


You are trying to call onload rather than assign an event handler. Here is a quick fix for you...

image.onload = (event) => {
  // ...
};

You will also find that the general Event type doesn't have width and height, so you may need to specialise the type for that too.

interface SizedEvent {
  width: number;
  height: number;
}

function isSizedEvent(e: any): e is SizedEvent {
  return (e && e.width !== undefined && e.height !== undefined);
}  

image.onload = (event) => {
  if (isSizedEvent(event)) {
    // event.width is now available
  }
};
like image 21
Fenton Avatar answered Oct 11 '22 21:10

Fenton