使用 Javascript 调整图像大小而不在 DOM 上渲染 canvas

Resizing a image with Javascript without rendering a canvas on the DOM

我在许多其他话题中看到了这个有趣的话题:Resize a Base-64 image in JavaScript without using canvas

然而,当我使用

创建屏幕外canvas时
const canvas = document.createElement('canvas');

结果图片是透明的,尺寸甚至不符合参数。 如果我使用 DOM 中的 canvas 一切正常

const canvas = document.getElementById('canvas');

这是我保持输入图像比例的调整大小函数:

resizeImage(file) {
    const canvas = document.createElement('canvas');
    // const canvas = document.getElementById('canvas');
    const context = (<HTMLCanvasElement>canvas).getContext('2d');
    // set maximum width and height of output image
    const maxW = 400;
    const maxH = 400;
    const img = new Image;

    img.onload = function () {
        const iw = img.width;
        const ih = img.height;
        const scale = Math.min((maxW / iw), (maxH / ih));
        const iwScaled = iw * scale;
        const ihScaled = ih * scale;
        console.log(iwScaled + ' ' + ihScaled);
        (<HTMLCanvasElement>canvas).width = iwScaled;
        (<HTMLCanvasElement>canvas).height = ihScaled;
        context.drawImage(img, 0, 0, iwScaled, ihScaled);
    }
    img.src = URL.createObjectURL(file);
    // retrieve output img in base64 format
    console.log((<HTMLCanvasElement>canvas).toDataURL());
}

它从 HTML 输入中获取一个文件 (File) 作为参数。 任何帮助将不胜感激,谢谢。

加载完成后,您将获得一个 Base-64 图像。

function resizeImage(file) {
      var canvas = document.createElement('canvas');
      var context = canvas.getContext('2d');
      var maxW = 400;
      var maxH = 400;
      var img = document.createElement('img');

      img.onload = function() {
        var iw = img.width;
        var ih = img.height;
        var scale = Math.min((maxW / iw), (maxH / ih));
        var iwScaled = iw * scale;
        var ihScaled = ih * scale;
        canvas.width = iwScaled;
        canvas.height = ihScaled;
        context.drawImage(img, 0, 0, iwScaled, ihScaled);
        console.log(canvas.toDataURL());
        document.body.innerHTML+=canvas.toDataURL();
      }
      img.src = URL.createObjectURL(file);
    }
    document.getElementById("file").addEventListener("change", function() {
      file = file.files[0];
      if (file) {
        resizeImage(file);
      }
    });
<input id="file" type="file">