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.
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!
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.
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.
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.).
HTMLImageElement worked for me:
image.onload = function (this: HTMLImageElement) {
const height = this.height;
const width = this.width;
console.log('Image size ', [width, height])
};
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
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With