使用 HTML5 Canvas 防止图像按比例缩放

Rul*_*awg 2 html canvas

我希望能够在 HTML5 画布元素上绘制图像,其中图像被调整为画布宽度但不调整高度。本质上,我希望它将高度裁剪为画布高度,而不是尝试缩放宽度和高度。

例如,如果我在 320 x 150 的画布上绘制图像。我希望我的图像缩小到 320 的宽度并显示高度的前 150 像素。

小智 5

您只需要计算图像纵横比:

var f = image.height / image.width;
var newHeight = canvas.width * f;
Run Code Online (Sandbox Code Playgroud)

然后使用重新计算的图像高度绘制目的地:

ctx.drawImage(image, 0, 0, image.width, image.height, // source size
                     0, 0, canvas.width, newHeight);  // destination size
Run Code Online (Sandbox Code Playgroud)

Canvas 将为您剪裁。

如果你想让目标垂直位置居中,你可以这样做:

var destY = (canvas.height - image.height) / 2;

ctx.drawImage(image, 0, 0, image.width, image.height,    // source size
                     0, destY, canvas.width, newHeight); // destination size
Run Code Online (Sandbox Code Playgroud)