反应图像多作物

问题描述

希望你一切顺利:)

我正在尝试使用 react-image-crop 库设置多个裁剪,但是很难理解其背后的逻辑。我已经阅读了文档并尝试了不同的方法,但它们似乎都不起作用。基本上,我想:

  1. 扫描图片
  2. 自动将其裁剪到 3 个不同的位置
  3. 并将它们发送到服务器

这是我的代码:

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,但我一直无法自动获得多个裁剪。请帮忙:(

解决方法

通过在异步函数(将信息发送到后端的函数)中创建一个逻辑来解决它。如果您遇到同样的问题,请随时发送消息,我会在这里发布:)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...