使用HTML5画布调整图像大小



我正在尝试用画布调整图像的大小。我的目标是在不改变比例的情况下生成一个尺寸为A x B、大小为M x N的图像,就像CSS包含的一样。例如,如果源图像是1000x1000,目的地是400x300,那么它应该在底部切掉一块100像素的通行费,这应该对应于源图像中的250像素。

我的代码如下:

const canvas = document.createElement('canvas');
const img = new Image();
img.src = promotedImage;
const FINAL_WIDTH = 400;
const FINAL_HEIGHT = 250;
const width = img.width;
const height = img.height;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, width, height, 0, 0, FINAL_WIDTH, FINAL_HEIGHT);
const finalImage = b64toFile(canvas.toDataURL("image/jpg"));

不过,这并不像我想的那样奏效。我显然使用drawImage不正确。对我来说,if在不调整大小的情况下将源复制到目标。

这是因为我需要在绘制之前调整画布的大小(更改尺寸(吗?请告知。

我也尝试过类似Mozilla图片上传的东西。它甚至可以缩放图像,但不会裁剪。此外,它将源正方形的大小调整为较小的目标侧,而不是剪裁它

设置图像源是异步的,可能非常快,但通常不够快,无法跟上仍在运行的代码。通常,为了使它们可靠地工作,您先设置一个onload处理程序,然后再设置src。画布元素默认为300x150,因此也需要调整大小。(Canvas遵循CORS。.crossOrigin = ''将我们设置为匿名,imgur有一个允许的CORS策略。否则,我们将无法在使用该片段中的第三方图像时将Canvas转换为图像。(

const MAX_WIDTH = 400;
const MAX_HEIGHT = 300;
const img = new Image();
img.crossOrigin = '';
img.onload = () => {
const wRatio = MAX_WIDTH / img.width;
const hRatio = MAX_HEIGHT / img.height;
var width, height;
if(wRatio > hRatio) {
width = MAX_WIDTH;
height = wRatio * img.height;
}
else {
width = hRatio * img.width;
height = MAX_HEIGHT;
}
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, width, height);
//const finalImage = b64toFile(canvas.toDataURL("image/jpg"));
const imgElement = document.createElement('img');
imgElement.src = canvas.toDataURL('image/jpg');
document.body.appendChild(imgElement);
};
img.src = 'https://i.imgur.com/TMeawxt.jpeg';
img { border: 1px solid red; }

最新更新