fengyuanchen / cropperjs

JavaScript image cropper.
https://fengyuanchen.github.io/cropperjs/
MIT License
13.15k stars 2.42k forks source link

dragMode: 'none'时,裁剪奇数尺寸的图片,会出现黑边 #1099

Closed ruimax closed 1 year ago

ruimax commented 1 year ago

复现代码:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=\, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.13/cropper.min.css"
    crossorigin="anonymous" referrerpolicy="no-referrer" />
  <script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.13/cropper.min.js" crossorigin="anonymous"
    referrerpolicy="no-referrer"></script>
</head>

<body>
  <div>
    <img id="image" src="https://metis-online.fbcontent.cn/metis-gnosis-question/images/XhZUZWzEMbSeMvXVEX9e2S.png">
  </div>
  <p>
    <button id="btn">crop</button>
  </p>
  <p>
    <img id="test2" crossOrigin="Anonymous" />
  </p>
  <script>
    const image = document.getElementById('image');
    const cropper = new Cropper(image, {
      aspectRatio: 16 / 9,
      dragMode: 'none',
      zoomOnWheel: false,
      autoCrop: false,
    });
    document.getElementById('btn').addEventListener('click', () => {
      const base64 = cropper.getCroppedCanvas().toDataURL('image/jpeg')
      const img = document.getElementById('test2')
      img.setAttribute('src', base64)
    })
  </script>
</body>

</html>

复现结果: image

看源代码,当dragMode为'none'时,cropped为false,此时返回的getSourceCanvas的结果,这个方法里translate的值带有小数,但是最后drawImage的坐标执行了Math.floor,导致图片在画布上出现了偏移,最后会出现一个黑边 image

如果是jpg的图片,可以直接设置fillColor为'#FFF',但是当图片时png的时候,就不行了

fengyuanchen commented 1 year ago

Duplicate of #551.

ruimax commented 1 year ago

Duplicate of #551.

看着不是一样的问题,551问题的解法里的rounded只有在cropped参数为false的时候生效,getSourceCanvas中没有使用rounded参数,我看的代码是1.6.0