Reputation: 177
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.
Upvotes: 12
Views: 24832
Reputation: 123
This worked for me:
img.onload = function () {
const { width, height } = this as GlobalEventHandlers & {
width: number
height: number
}
}
Upvotes: 0
Reputation: 171
In Angular 14.1, I was also able to simply cast to HTMLImageElement
...
var image = new Image();
image.onload = (onLoadResult) => {
const img = onLoadResult.target as HTMLImageElement;
// do cool stuff
}
image.src = screenShotDataUrl;
Upvotes: 1
Reputation: 2146
HTMLImageElement worked for me:
image.onload = function (this: HTMLImageElement) {
const height = this.height;
const width = this.width;
console.log('Image size ', [width, height])
};
Upvotes: 2
Reputation: 250922
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
}
};
Upvotes: 13