'React image multi crops

Hope you're doing fine :)

I'm trying to set multiple crops with react-image-crop library, but it's getting really difficult to understand the logic behind it. I've read the documentation and trying different approaches but none of them seems to work. Basically, I want to:

  1. Scan a picture
  2. Crop it in 3 different places automaticaly
  3. And send them to the server

This is my code:

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;

I've managed to get the cropped image to base64, but I'm stuck in getting multiple crops automatically. Please help :(



Solution 1:[1]

Resolved it simply by creating a logic inside an async function (the one that sends information to the backend). If you're stuck with the same problem, feel free to send a message and I'll post it here :)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 André Rodrigues