将图像缩放并裁剪为Javascript中的指定尺寸

时间:2020-08-09 04:37:36

标签: javascript image

我正在尝试将图像缩放到指定的宽度和高度,而不会扭曲Javascript中的图像。

我目前有这个:https://codesandbox.io/s/practical-diffie-fkzwb

我正在创建具有所需宽度和高度的画布,然后将源图像平移。在此示例中,源图像是非常宽的图像,而第一个目标图像的高度大于宽度,但是按比例缩小。

我正在尝试剪裁图像左右两侧的一部分以防止变形,并仍然在新画布中捕获大部分图像。用于绘制新图像的当前代码如下:

ctx.drawImage(
      image,                 // Source image
      sx + wdx,              // Start x in source
      sy,                    // Start y in source
      w - wdx * 2,           // Source width in dest
      h,                     // Source height in dest
      dx,                    // Start x in dest
      dy,                    // Start y in dest
      desiredWidth,          // Dest width
      desiredHeight          // Dest height
    );

问题是图像看起来失真。我尝试调整源字段的开始和结束,但是在提出正确的功能来适当缩放这些图像时遇到了困难。

如何缩放这些图像并将其调整为所需的宽度和高度?

1 个答案:

答案 0 :(得分:1)

我认为您缺少的关键组件是考虑到图像的宽高比。我在您的代码沙箱上尝试过此操作,我认为它可以满足您的要求:

let aspectRatio = Math.min(desiredWidth / w, desiredHeight / h);
    let actualW = (aspectRatio * w);
    let actualH = (aspectRatio * h);

    ctx.drawImage(
      image, // Src image.
      0, // Start x in source
      0, // Start y in source
      w, // Source width in dest
      h, // Source height in dest
      (desiredWidth - actualW) / 2, // Start x in dest
      (desiredHeight - actualH) / 2, // Start y in dest
      actualW, // Dest width
      actualH // Dest height
    );