希望你做的很好:)
我正在尝试用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, 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,
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上,但是我坚持自动获取多种农作物。请帮助:(