将 HTMLImageElement 分配给 TexImageSource

Assigning HTMLImageElement to TexImageSource

我有一个类型为 TexImageSource 的变量,我正在尝试为其设置一个 HTMLImageElement。

据我了解 TexImageSource 是:

type TexImageSource = ImageBitmap | ImageData | HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | OffscreenCanvas

这是我的图片加载代码:

return new Promise((resolve: Function, reject: Function) => {
    let image: HTMLImageElement = new Image();
    
    image.onload = () => { resolve(image); };
    image.onerror = error => { reject(error); };
    image.src = url;
});
const texture: TexImageSource = loadedImage;

我得到的错误是:

Type 'unknown' is not assignable to type 'TexImageSource'.
  Type '{}' is missing the following properties from type 'OffscreenCanvas': height, width, convertToBlob, getContext, and 4 more.

我真的不明白为什么会出现此错误,请问有人能解释一下情况吗?

我不是打字专家,但我认为你需要声明 Promise

的类型

function loadImage(url: string): Promise<HTMLImageElement> {
    return new Promise((resolve: Function, reject: Function) => {
        let image: HTMLImageElement = new Image();
        
        image.onload = () => { resolve(image); };
        image.onerror = error => { reject(error); };
        image.src = url;
    });
}

async function main() {
    const loadedImage = await loadImage('someImage.png');
    const texture: TexImageSource = loadedImage;
}

如果我改变

function loadImage(url: string): Promise<HTMLImageElement> {

function loadImage(url: string) {

然后我得到了你的问题显示的错误

你也可以这样做

function loadImage(url: string) {
    return new Promise<HTMLImageElement>((resolve: Function, reject: Function) => {