【问题标题】:Image() does not accept width and heightImage() 不接受宽度和高度
【发布时间】:2021-03-08 22:03:50
【问题描述】:

我遇到了一个非常奇怪的问题。我使用 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

然后一切正常

【问题讨论】:

  • 试试image.style.width = width + 'px';
  • 也值得检查任何 CSS 样式
  • @Barmar 使用样式,参数设置为原来的高宽
  • @t3dodson 我没有连接任何样式。
  • @Fraybyl 我很确定还有其他问题。我不知道您如何将 _Assets 数组附加到 dom。我为您的代码做了一个类似的例子,它正在工作。 jsfiddle.net/c4opfn8a/2

标签: javascript image


【解决方案1】:

这很正常,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>

请注意,如果您打算将此图像仅用于在画布上绘图,则存在ImageBitmap接口,可让您在构建时设置尺寸,但此选项目前仅在Chrome浏览器中可用,尽管您可以轻松编写一个 polyfill,为其他浏览器返回一个调整大小的画布。

(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>

【讨论】:

  • 我理解并知道这一点,但我希望图像在加载后立即更改为我需要的分辨率。
  • 按照预期使用方法:传递您的尺寸。
猜你喜欢
  • 1970-01-01
  • 2017-03-03
  • 2011-08-06
  • 2014-04-29
  • 2014-02-14
  • 2016-06-07
  • 2022-01-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多