【问题标题】:Scaling cropped area up onto a HTML canvas [duplicate]将裁剪区域缩放到 HTML 画布上 [重复]
【发布时间】:2021-03-03 23:25:21
【问题描述】:

谁擅长数学?

我有一个像这样的图像和画布......

底部的 Canvas 大约比上面的裁剪框大 10 倍,但我们正在放大裁剪区域。

我已经研究出如何让裁剪区域的宽度始终为 100%,这是代码...

const canvas = document.createElement('canvas')
const scaleX = image.naturalWidth / image.width
const scaleY = image.naturalHeight / image.height
const ctx = canvas.getContext('2d')

const xCropScale = crop.width / image.width

canvas.width = crop.width * scaleX + image.naturalWidth * (1 - xCropScale)
canvas.height = crop.height * scaleY

ctx.drawImage(
  image,
  crop.x * scaleX,
  crop.y * scaleY,
  crop.width * scaleX,
  crop.height * scaleY,
  0,
  0,
  crop.width * scaleX + image.naturalWidth * (1 - xCropScale),
  crop.height * scaleY
)

我遇到的问题是根据我们裁剪的内容以及裁剪区域大小的增加来缩放高度。如您所见,屏幕截图沿 X 轴是正确的,但 Y 轴需要缩放以不使图像变形。

image.naturalWidth 是我上传的图片宽度(也是底部图片宽度),以 1000 像素为单位,而 image.width 是大约 200 像素的顶部图片宽度。

谢谢

【问题讨论】:

    标签: javascript math canvas


    【解决方案1】:

    注意:不知道您对裁剪后的图像的下一步是什么:

    考虑缩放裁剪的图像,而不是自己计算尺寸。

    例如,将裁剪后的图像加倍...

    crop.scale(2,2);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多