我在其他许多人中看到了这个有趣的线程:在不使用画布的情况下在JavaScript中调整Base-64图像的大小
但是,当我使用创建一个屏幕外画布
const canvas = document.createElement('canvas');
Run Code Online (Sandbox Code Playgroud)
结果图像是透明的,大小甚至不匹配参数.如果我在DOM的画布上画一切都很好
const canvas = document.getElementById('canvas');
Run Code Online (Sandbox Code Playgroud)
这是我的调整大小功能,保持输入图像比例:
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 …Run Code Online (Sandbox Code Playgroud)