我正在尝试在react应用程序中裁剪图像。我目前使用的是一个名为react- image -crop的库,但似乎裁剪后的图像在浏览器上的裁剪区域大小完全相同,这意味着如果我调整浏览器窗口的大小,图像的相同区域会变成不同的大小。有没有办法既能保持原始图像的分辨率,又能在客户端进行裁剪?下面的图片是在不同浏览器大小下对图片的相同区域进行裁剪的结果。
我主要使用react-image-crop开箱即用,带有以下裁剪参数
const [crop, setCrop] = useState({unit: '%', width: 100, aspect: 16 / 9 });

发布于 2020-06-26 12:32:21
实际上我也有同样的问题,我也使用了react-image-crop。我目前的解决方案是在px中创建一个具有静态大小的模式作为裁剪窗口。因此,如果窗口大小较小,则模式溢出将被激活。
或多或少像这样:

因此,滚动条会根据窗口大小动态变化,不会影响图像大小。
如果有一个真正的更好的解决方案,也许我也想听听:)
发布于 2020-07-01 00:33:44
在演示的钩子版本中,替换getResizedCanvas (并将其移动到react模块中)可以修复该问题
const getResizedCanvas = () => {
const scaleX = imgRef.current.naturalWidth / imgRef.current.width;
const scaleY = imgRef.current.naturalHeight / imgRef.current.height;
const tmpCanvas = document.createElement("canvas");
tmpCanvas.width = Math.ceil(crop.width*scaleX);
tmpCanvas.height = Math.ceil(crop.height*scaleY);
const ctx = tmpCanvas.getContext("2d");
const image = imgRef.current;
ctx.drawImage(
image,
crop.x * scaleX,
crop.y * scaleY,
crop.width * scaleX,
crop.height * scaleY,
0,
0,
crop.width*scaleX,
crop.height*scaleY,
);
return tmpCanvas;
}发布于 2021-06-02 18:29:29
我也有同样的问题。但是在画布和drawImage方法中添加缩放的高度和宽度对我来说是有效的。
查看下面的屏幕截图。
const createCropPreview = async (image, crop, fileName) => {
const scaleX = image.naturalWidth / image.width;
const scaleY = image.naturalHeight / image.height;
const canvas = document.createElement("canvas");
canvas.width = Math.ceil(crop.width * scaleX);
canvas.height = Math.ceil(crop.height * scaleY);
const ctx = canvas.getContext("2d");
ctx.drawImage(
image,
crop.x * scaleX,
crop.y * scaleY,
crop.width * scaleX,
crop.height * scaleY,
0,
0,
crop.width * scaleX,
crop.height * scaleY
);
return new Promise((resolve, reject) => {
canvas.toBlob((blob) => {
if (blob) {
blob.name = fileName;
window.URL.revokeObjectURL(previewUrl);
const obj = window.URL.createObjectURL(blob);
setPreviewUrl(obj);
props.setImg(obj, blob);
}
}, "image/jpeg");
});
};https://stackoverflow.com/questions/62585425
复制相似问题