Home > Mobile >  Why 'drawImage' does not accept parameters?
Why 'drawImage' does not accept parameters?

Time:09-22

In this line:

context.drawImage(img, img.width, img.height)

got this error:

This expression is not callable.
  Each member of the union type '{ (image: CanvasImageSource, dx: number, dy: number): void; (image: CanvasImageSource, dx: number, dy: number, dw: number, dh: number): void; (image: CanvasImageSource, sx: number, sy: number, sw: number, sh: number, dx: number, dy: number, dw: number, dh: number): void; } | { ...; }' has signatures, but none of those signatures are compatible with each other.ts(2349)
(property) drawImage: {
    (image: Image | Canvas, dx: number, dy: number): void;
    (image: Image | Canvas, dx: number, dy: number, dw: number, dh: number): void;
    (image: Image | Canvas, sx: number, sy: number, sw: number, sh: number, dx: number, dy: number, dw: number, dh: number): void;
} | {
    ...;
}

And here is the method signature:

const drawFrame = (
    context: CanvasRenderingContext2D | SKRSContext2D,
    positions: typeof startPositions,
    title: string,
    text: string,
    img: Image,
    locale?: string
) => {

parameters should fit. Then what is wrong?

using napi-rs/canvas

import {
    createCanvas,
    GlobalFonts,
    Image,
    loadImage,
    SKRSContext2D,
} from '@napi-rs/canvas'

CodePudding user response:

The issue is that you use the generic CanvasRenderingContext2D definition, which expects for its drawImage() method a generic CanvasImageSource member which is made of the union HTMLOrSVGImageElement | HTMLVideoElement | HTMLCanvasElement | ImageBitmap.
The Image object that loadImage() returns doesn't match that union, it does miss some properties from HTMLImageElement that makes it no quite a valid value for HTMLOrSVGImageElement.

However the library you do use has already defined its own SKRSContext2D as being an extension of the CanvasRenderingContext2D interface, with its own drawImage() method that does accept Image (and Canvas) as source. So declaring your context parameter as SKRSContext2D only will make TS happy with your code:

const drawFrame = (
    context: SKRSContext2D,
    positions: typeof startPositions,
    title: string,
    text: string,
    img: Image,
    locale?: string
) => {

Simplified TS-playground.

  • Related