簡體   English   中英

Image() 不接受寬度和高度

[英]Image() does not accept width and height

我遇到了一個非常奇怪的問題。 我使用 promises 方法來異步加載圖像等。

loadImage(name, src, width, height) {
    return new Promise((resolve, reject) => {
        const image = new Image();
        this._Assets[name] = image;
        image.onload = () => resolve(name);
        image.onerror = () => reject(`failed to load ${name}`);
        image.src = src;
        if (width != void 0) image.width = width;
        if (height != void 0) image.height = height;
    });
}

如您所見,我正在為圖像分配寬度和高度參數,但它不起作用。 圖像在屬性中具有寬度和高度,但是圖像本身通過 context.drawimage 使用 naturalwidth 和 naturalheight 顯示。 但是,當我在加載圖像后嘗試分配給圖像時。 它給了我一個錯誤:無法設置屬性寬度,但圖像本身被裁剪。 我已經嘗試立即將參數傳遞給新圖像(寬度,高度),但它沒有得到任何地方。 如果我們嘗試在drawimage中傳遞參數

assets[`bg`].width
assets[`bg`].height

然后一切正常

這很正常, CanvasRenderingContext2d.drawImage根本不會查看 HTMLImageElement 的widthheight屬性,只有 x 和 y 參數,它將使用源圖像的固有尺寸。

但是,此方法帶有一些不同的簽名,可讓您設置不同的尺寸:

 const image = new Image(); image.src = "https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png"; image.onload = e => { const ctx = document.querySelector( "canvas" ).getContext( "2d" ); ctx.drawImage( image, 0, 0 ); // use intrinsic dimensions ctx.drawImage( image, 0, 0, 150, 150 ); // take the full source and resize to 150x150 ctx.drawImage( image, 0, 0, 350, 350, 160, 0, 50, 50 ); // take the source rectangle at 0,0,350,350 and draw it in a 50x50 rectangle }
 <canvas id="canvas" width="500" height="500"></canvas>

請注意,如果您打算將此圖像僅用於在 canvas 上繪圖,則存在ImageBitmap接口,可讓您在構造時設置尺寸,但此選項目前僅在 Chrome 瀏覽器中可用,盡管您可以輕松編寫 polyfill為其他瀏覽器返回一個調整大小的 canvas。

 (async () => { const blob = await fetch( "https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png" ).then( (resp) => resp.blob() ); const image = await createImageBitmap( blob, { resizeWidth: 150, resizeHeight: 150 } ); const ctx = document.querySelector( "canvas" ).getContext( "2d" ); ctx.drawImage( image, 0, 0 ); // resized })().catch( console.error );
 <canvas id="canvas" width="500" height="500"></canvas>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM