You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用react-image-crop实现图片缩放裁剪,解决缩放后裁切异常问题

问题根因

当前代码仅完成了原图尺寸和页面渲染图片尺寸的比例换算,没有将react-image-crop组件的scale缩放参数纳入裁剪坐标的计算,导致缩放后裁剪结果错位。

修复步骤

  1. 调用裁剪函数时,将react-image-crop组件绑定的scale状态值作为参数传入
  2. 调整drawImage方法的原图裁剪区域计算逻辑,将缩放比例纳入换算

修改后的完整代码如下:

// 调用函数时记得传入当前的scale值,比如 getCroppedImg(image, crop, fileName, scale)
const getCroppedImg = (image: HTMLImageElement, crop: any, fileName: string, scale: number = 1) => {
  const canvas = document.createElement('canvas')

  const scaleX: number = image.naturalWidth / image.width
  const scaleY: number = image.naturalHeight / image.height

  const ctx = canvas.getContext('2d')

  const pixelRatio = window.devicePixelRatio

  canvas.width = crop.width * pixelRatio
  canvas.height = crop.height * pixelRatio

  if (ctx !== null) {
    ctx.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0)
    ctx.imageSmoothingQuality = 'high'

    ctx.drawImage(
      image,
      // 纳入scale参数计算原图裁剪起点
      (crop.x / scale) * scaleX,
      (crop.y / scale) * scaleY,
      // 纳入scale参数计算原图裁剪尺寸
      (crop.width / scale) * scaleX,
      (crop.height / scale) * scaleY,
      0,
      0,
      crop.width,
      crop.height
    )
  }

  // 作为Base64返回的代码
  // const base64Image = canvas.toDataURL("image/jpeg");
  // return base64Image;

  // 作为Blob返回
  return new Promise((resolve, reject) => {
    canvas.toBlob(
      (blob: Blob | null) => {
        if (blob) {
          blob.name = fileName
          const newImg = URL.createObjectURL(blob)
          resolve(newImg)
        }
        reject(new Error('裁剪生成图片失败'))
      },
      'image/png',
      1
    )
  })
}

补充说明

如果你同时用到了react-image-crop的旋转功能,还需要在裁剪逻辑中加入rotate参数的换算,通过ctx.rotate先对画布做旋转处理再绘制图片即可。

内容的提问来源于stack exchange,提问作者Isaac Méndez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 03:09:03