对我来说,这实际上是固定的(使用钩子)。基本上,我正在计算画布大小,同时考虑到当前显示设备的物理像素的窗口分辨率和 CSS 像素的分辨率。
const canvas = document.createElement('canvas')
const crop = completedCrop
const scaleX = image.naturalWidth / image.width
const scaleY = image.naturalHeight / image.height
const ctx = canvas.getContext('2d')
const pixelRatio = window.devicePixelRatio
canvas.width = scaleX * crop.width * pixelRatio
canvas.height = scaleY * crop.height * pixelRatio
ctx.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0)
ctx.imageSmoothingQuality = 'high'
ctx.drawImage(
image,
crop.x * scaleX,
crop.y * scaleY,
crop.width * scaleX,
crop.height * scaleY,
0,
0,
crop.width * scaleX,
crop.height * scaleY
)
您还可以将画布 blob 导出为 png(无损)而不是 jpeg,这将为您提供更好的图像。
canvas.toBlob(
blob => {
const img = URL.createObjectURL(blob)
// do whatever you want...
},
'image/png',
1
)