Argument of type ‘HTMLElement’ is not assignable to parameter of type ‘CanvasImageSource’

You have to tell the compiler that the img variable is being set as an HTMLImageElement.

The ctx.drawImage method expects a :

HTMLOrSVGImageElement | HTMLVideoElement | HTMLCanvasElement | ImageBitmap;

If your P43 is a canvas you have to do:

const img = document.getElementById("P43") as HTMLCanvasElement;

if it’s an image element:

const img = document.getElementById("P43") as HTMLImageElement;

It would be even better to actually check that the element is in fact the right type of Element. You can do this with instanceof. The TypeScript compiler will also pick up the if statement, and inside the if statement the img variable will be a HTMLCanvasElement for the compiler, so explicit casting is no longer necessary:

const img = document.getElementById("P43");

if (img instanceof HTMLImageElement) {
  ctx.drawImage(img,0,0,106,50);
} else {
  // wrong element!
}

Leave a Comment