如何解决反应图像多作物
希望你一切顺利:)
我正在尝试使用 react-image-crop 库设置多个裁剪,但是很难理解其背后的逻辑。我已经阅读了文档并尝试了不同的方法,但它们似乎都不起作用。基本上,我想:
这是我的代码:
const CameraComp = () => {
const [upImg,setUpImg] = useState();
const imgRef = useRef(null);
const previewCanvasRef = useRef(null);
const [crop,setCrop] = useState({
unit: "px",width: 30,height: 30,aspect: 16 / 9
});
const [completedCrop,setCompletedCrop] = useState(null);
const onLoad = useCallback((img) => {
imgRef.current = img;
},[]);
useEffect(() => {
if (!completedCrop || !previewCanvasRef.current || !imgRef.current) {
return;
}
const image = imgRef.current;
const canvas = previewCanvasRef.current;
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 = crop.width * pixelRatio;
canvas.height = crop.height * pixelRatio;
ctx.setTransform(pixelRatio,pixelRatio,0);
ctx.imageSmoothingQuality = "high";
ctx.drawImage(
image,crop.x * scaleX,crop.y * scaleY,crop.width * scaleX,crop.height * scaleY,crop.width,crop.height
);
const base64Image = canvas.toDataURL("image/jpeg");
},[completedCrop]);
const handleTakePhoto = (dataUri) => setUpImg(dataUri);
console.log(completedCrop);
return (
<Container id="scanner-container">
<h1>Scanner</h1>
<Camera
onTakePhoto={(dataUri) => {
handleTakePhoto(dataUri);
}}
/>
<ReactCrop
disabled
onImageLoaded={onLoad}
src={upImg}
crop={crop}
onComplete={(c) => setCompletedCrop(c)}
/>
<div>
<canvas
ref={previewCanvasRef}
style={{
width: Math.round(completedCrop?.width ?? 0),height: Math.round(completedCrop?.height ?? 0)
}}
/>
</div>
</Container>
);
};
export default CameraComp;
我已经设法将裁剪后的图像转换为 base64,但我一直无法自动获得多个裁剪。请帮忙:(
解决方法
通过在异步函数(将信息发送到后端的函数)中创建一个逻辑来解决它。如果您遇到同样的问题,请随时发送消息,我会在这里发布:)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。