您的当前位置:首页>全部文章>文章详情

【React】React前端图片裁剪组件

CrazyPanda发表于:2024-03-29 17:38:16浏览:311次TAG:

前端图片裁剪已经是很常见的需求了,在 react 的项目中推荐使用 react-image-crop 库,能勾勒出裁剪区域、宽高比例限制等等,但是还是有很多东西需要我们来做的,比如以下问题:

react-image-crop

react-image-crop 的基本使用

import ReactCrop from "react-image-crop";
import "react-image-crop/dist/ReactCrop.css";

const cropOnChange = (newCrop: any) => {};

const onImageLoaded = (image: any) => {};

<ReactCrop
  src={src}
  crop={crop}
  onChange={cropOnChange}
  onImageLoaded={onImageLoaded}
>
  {props.children}
</ReactCrop>;

限制图片的最小宽高

如果连展示位的最小宽高都不满足,那还裁剪什么

export function getImgSize(src: any, w: number, h: number): Promise<any> {
  return new Promise((resolve, reject) => {
    if (!src) return;
    const img = document.createElement("img");
    img.src = src;
    img.onload = function() {
      const { width, height } = img;
      if (width < w || height < h) {
        reject(`请上传宽大于${w},高大于${h}的图片`);
        return;
      }
      resolve({ width, height, img });
    };
  });
}

原图按比例缩放

有的图片尺寸很大,但是我们要显示在一个屏幕之中,那么要采取原图按比例缩放,所以定高和定宽成了一个选择,那么会出现另一个问题,后面再说。

假设我们决定了定高:

const initImage = (image: any) => {
  const { width, height } = image;
  // 计算出现在高度和定高的比例
  let radio = height / config.imgMinWH.h;
  // 那么现在宽度值
  let cW = width / radio,
    cH = config.imgMinWH.h;
  if (width === 900) {
    cW = 900;
    radio = 1;
    let wRadio = cW / width;
    cH = height * wRadio;
  }
  // 设置image的宽高
  image.width = cW;
  image.height = cH;
  setScaleRadio(radio);
  setCrop({ ...crop, ...{ x: 0, y: 0, width: cW, unit: "px" } });
};

然后按照比例在原图上裁剪

裁剪的话使用 canvas 来裁剪,那么有个很重要的问题,就是图片的跨域问题,图片不在一个域下的话,使用 canvas 会污染画布,这个时候别急,将使用其他方法来解决这个问题,oss 的话开启图片的 get 操作即可

const canvas = document.createElement("canvas");
const ctx: any = canvas.getContext("2d");
const canvasImage = () => {
  const img = new Image();
  img.crossOrigin = "Anonymous";
  img.src = signatureUrl(props.src || "", false);
  common.showLoading();
  img.onload = function() {
    const { x, y, width, height } = crop;
    canvas.width = Math.floor(width * scaleRadio);
    canvas.height = Math.floor(height * scaleRadio);
    ctx.drawImage(
      img,
      Math.floor(x * scaleRadio),
      Math.floor(y * scaleRadio),
      img.width,
      img.height,
      0,
      0,
      img.width,
      img.height
    );
    getImageFileInfo().then(fileInfo => {
      // 上传图片到接口
      uploadImage(fileInfo);
    });
  };
};
const getImageFileInfo = (): Promise<any> => {
  return new Promise((resolve, reject) => {
    // 将canvas转成图片base64的url,可以直接打开
    // console.log(canvas.toDataURL('image/png'));
    // 将canvas转成Blob格式的二进制数据
    canvas.toBlob(blob => {
      if (!blob) {
        console.error("Canvas is empty");
        return;
      }
      resolve(blob);
    });
  });
};
  • 使用 ajax 请求图片来解决跨域

const canvas = document.createElement("canvas");
const ctx: any = canvas.getContext("2d");
const requestImg = () => {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  const xhr = new XMLHttpRequest();
  xhr.onload = function() {
    const url = URL.createObjectURL(this.response);
    const img = new Image();
    img.onload = function() {
      canvas.width = img.naturalWidth;
      canvas.height = img.naturalHeight;
      ctx.drawImage(this, 0, 0, img.naturalWidth, img.naturalHeight);
      URL.revokeObjectURL(url);
      const base64 = canvas.toDataURL();
      console.log(base64);
    };
    img.src = url;
  };
  xhr.open("GET", props.src || "", true);
  xhr.responseType = "blob";
  xhr.send();
};

image-core 完整组件

import React, { useState, useEffect } from "react";
import ReactCrop from "react-image-crop";
import { SuperUpload } from "@/components/Base";
import defaultConfig from "./config";
import "react-image-crop/dist/ReactCrop.css";
import { multipartUpload } from "@/components/Upload/method";
import { signatureUrl } from "@/utils/oss";

const style = require("./index.less");

export interface CoreImageInterface {
  imgMinWH?: { w: number, h: number };
  visible: boolean;
  value?: string;
  config?: any;
  src?: string;
  aspect?: number;
  openCore: Function;
  srcChange: Function;
  onCancel?: Function;
  onChange?: Function;
}

export function getImgSize(src: any, w: number, h: number): Promise<any> {
  return new Promise((resolve, reject) => {
    if (!src) return;
    const img = document.createElement("img");
    img.src = src;
    img.onload = function() {
      const { width, height } = img;
      if (width < w || height < h) {
        reject(`请上传宽大于${w},高大于${h}的图片`);
        return;
      }
      resolve({ width, height, img });
    };
  });
}

export function makeUploadName() {
  return "core-image/" + +new Date();
}

const canvas = document.createElement("canvas");
const ctx: any = canvas.getContext("2d");

const CoreImage: React.FC<CoreImageInterface> = props => {
  const [crop, setCrop]: [any, Function] = useState({
    aspect: props.aspect || 3 / 1
  });
  const [scaleRadio, setScaleRadio] = useState(1);
  const [visible, setVisible] = useState(false);
  const [src, setSrc] = useState("");
  const config = { ...defaultConfig, ...props.config };

  useEffect(() => {
    setVisible(props.visible);
    if (!props.visible) {
      setCrop({ aspect: props.aspect || 3 / 1 });
      setSrc("");
      return;
    }
    initCrop();
  }, [props.visible]);

  const initCrop = () => {
    const img = new Image();
    const src = signatureUrl(props.src || "", false);
    img.src = src;
    img.onload = function() {
      setSrc(src || "");
    };
  };

  const initImage = (image: any) => {
    const { width, height } = image;
    let radio = height / config.imgMinWH.h;
    let cW = width / radio,
      cH = config.imgMinWH.h;
    if (width === 900) {
      cW = 900;
      radio = 1;
      let wRadio = cW / width;
      cH = height * wRadio;
    }
    image.width = cW;
    image.height = cH;
    setScaleRadio(radio);
    setCrop({ ...crop, ...{ x: 0, y: 0, width: cW, unit: "px" } });
  };

  const onImageLoaded = (image: any) => {
    initImage(image);
  };

  const cropOnChange = (newCrop: any) => {
    if (newCrop.width * scaleRadio < config.imgMinWH.w) return;
    setCrop(newCrop);
    // console.log(crop);
  };

  const canvasImage = () => {
    const img = new Image();
    img.crossOrigin = "Anonymous";
    img.src = signatureUrl(props.src || "", false);
    common.showLoading();
    img.onload = function() {
      const { x, y, width, height } = crop;
      canvas.width = Math.floor(width * scaleRadio);
      canvas.height = Math.floor(height * scaleRadio);
      ctx.drawImage(
        img,
        Math.floor(x * scaleRadio),
        Math.floor(y * scaleRadio),
        img.width,
        img.height,
        0,
        0,
        img.width,
        img.height
      );
      getImageFileInfo().then(fileInfo => {
        uploadImage(fileInfo);
      });
    };
  };

  const uploadImage = (fileInfo: Blob) => {
    const fileName = makeUploadName();
    multipartUpload({ fileName, fileInfo }).then((res: any) => {
      common.hideLoading();
      props.onChange && props.onChange(res.name);
    });
  };

  // ajax请求图片来解决跨域
  // const requestImg = () => {
  //   ctx.clearRect(0, 0, canvas.width, canvas.height);
  //   const xhr = new XMLHttpRequest();
  //   xhr.onload = function() {
  //     const url = URL.createObjectURL(this.response);
  //     const img = new Image();
  //     img.onload = function() {
  //       canvas.width = img.naturalWidth;
  //       canvas.height = img.naturalHeight;
  //       ctx.drawImage(this, 0, 0, img.naturalWidth, img.naturalHeight);
  //       URL.revokeObjectURL(url);
  //       const base64 = canvas.toDataURL();
  //       console.log(base64);
  //     };
  //     img.src = url;
  //   };
  //   xhr.open('GET', props.src || '', true);
  //   xhr.responseType = 'blob';
  //   xhr.send();
  // };

  const getImageFileInfo = (): Promise<any> => {
    return new Promise((resolve, reject) => {
      // console.log(canvas.toDataURL('image/png'));
      canvas.toBlob(blob => {
        if (!blob) {
          console.error("Canvas is empty");
          return;
        }
        resolve(blob);
      });
    });
  };

  const openCore = () => {
    if (props.src) props.openCore();
  };

  const onCancel = () => {
    props.onCancel && props.onCancel();
  };

  const onConfirm = () => {
    canvasImage();
  };

  return (
    <div>
      <>
        <div className={style.showBox}>
          <img
            style={{
              width: `${config.thumbImageWH.w}px`,
              height: `${config.thumbImageWH.h}px`
            }}
            src={signatureUrl(props.value || "")}
            alt=""
          />
          <div className={style.againOp}>
            <SuperUpload
              accept=".png,.jpg"
              isSelect={true}
              showUploadList={false}
              listType="text"
              imgMinWH={config.imgMinWH}
              imgText={<div className={style.btn}>重新上传</div>}
              onChange={res => props.srcChange(res)}
            ></SuperUpload>
            <div onClick={openCore} className={style.btn}>
              裁剪头图
            </div>
          </div>
        </div>
      </>
      <>
        {visible && src ? (
          <div className={style.container}>
            <div className={style.core}>
              <ReactCrop
                src={src}
                crop={crop}
                onChange={cropOnChange}
                onImageLoaded={onImageLoaded}
              >
                {props.children}
              </ReactCrop>
              <div
                style={{
                  top: `${crop.y + crop.height / 2 - 15.5}px`,
                  left: `${crop.x + crop.width / 2 - 46}px`
                }}
                className={style.size}
              >{`${Math.floor(crop.width * scaleRadio)} × ${Math.floor(
                crop.height * scaleRadio
              )}`}</div>
              <div
                style={{
                  top: `${crop.height + crop.y + 10}px`,
                  left: `${crop.width + crop.x - 146}px`
                }}
                className={style.op}
              >
                <div onClick={onCancel} className={style.btn}>
                  取消
                </div>
                <div onClick={onConfirm} className={style.btn}>
                  确定
                </div>
              </div>
            </div>
          </div>
        ) : null}
      </>
    </div>
  );
};

export default CoreImage;


原文链接https://blog.csdn.net/qq_42036203/article/details/104882489

猜你喜欢

【AntDesignPro】使用高德地图设置考勤区域
参考高德开放平台https://lbs.amap.com/api/javascript-api-v2/guide/abc/amap-react功能要求:使用AntDesignPro开发系统管理端,考勤模块需要设置APP考勤打卡区域,需要页面显示地图定位并设置考勤范围(地图上画圈),以便APP在画圈范围内打卡使用。1、 准备2、 下载react类组件代码参考官网流程,可正常加载出地图组件,下面是我的页面和组件文件组件文件3、 安装并引入AmAP Loadernpm&nbsp;i&nbsp;@ama
发表于:2023-12-14 浏览:762 TAG:
【React】react页面加载远程css和js
在React中,您可以使用componentDidMount生命周期方法来动态加载远程CSS和JavaScript文件。代码如下import&nbsp;React,&nbsp;{&nbsp;Component&nbsp;}&nbsp;from&nbsp;&#39;react&#39;; &nbsp; class&nbsp;DynamicResources&nbsp;extends&nbsp;Component&nbsp;{ &nbsp;&nbsp;componentDidMount()&amp;nbs
发表于:2024-05-15 浏览:273 TAG:
【React】如何在 React 类中声明常量?
使用 react 开发应用程序时,有必要声明常量来存储在组件或应用程序的整个生命周期中保持不变的值。常量可以帮助提高代码可读性,提供管理共享值的中心位置,并增强可维护性。在本文中,我们将探讨如何在 react 类组件中声明常量。导入 React首先,我们假设您已经设置了 React 环境并且有一个可供使用的类组件。在声明常量之前,请确保您已导入必要的库。这包括导入 React,它是在 React 中构建用户界面的核心库。import&nbsp;React&nbsp;from&nbsp;&#39;
发表于:2024-04-16 浏览:302 TAG:
【AntDesignPro】Ant Design Pro学习记录—DrawerForm的使用
在AntDesignPro中,ModalForm和DrawerForm是我最常用的两个表单组件,配置上,他们有很多相同的地方,也有差异的地方,相比较而言,DrawerForm我使用的更多。ModalForm&lt;ModalForm &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;title={标题} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;width={600} &nbsp;&nbsp;&amp;n
发表于:2024-05-17 浏览:468 TAG:
【AntDesignPro】AntDesignPro使用原生js,箩筐地图的使用
项目需要把高德地图替换成箩筐地图,WEB前端使用的ant design pro,高德地图有相关的react demo,而箩筐地图只有原生js,结合上一篇文章【AntDesignPro】使用高德地图设置考勤区域,把高德地图修改为箩筐地图,实现考勤范围设置。1 html使用箩筐地图参考上一篇文章【html】箩筐地图的使用,设置考勤范围,了解实现考勤范围设置需要用到的箩筐地图接口。2 ant design pro加载原生js这个是实现功能的核心,只有js正确加载上了,地图的功能才能够正常使用。结合an
发表于:2024-02-08 浏览:472 TAG:
【AntDesignPro】Ant Design Pro学习记录—默认主题配色修改
&nbsp;版本:&nbsp;Ant Design Pro V5先参考下官网定制主题 - Ant Design再参考这篇文章antd pro 修改全局样式_tankpanv的博客-CSDN博客_antd修改全局样式最后自己实验:第一步,在config.ts文件中配置theme:&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&#39;primary-color&#39;:&nbsp;defaultSettings.primaryColor, &nbsp;&nbsp;},这种配置需
发表于:2023-11-28 浏览:786 TAG:
【AntDesignPro】Ant Design Pro学习记录—ModalForm的使用(二)
&nbsp;目录一、ModalForm高度设置二、ModalForm点击阴影背景,不隐藏弹框三、ProFormSelect联动四、ProFormText关联赋值一、ModalForm高度设置在modalProps中设置bodyStyle:{height:500,overflowY:&#39;scroll&#39;}编辑效果如下:编辑二、ModalForm点击阴影背景,不隐藏弹框同样在modalProps里面,配置maskClosable: false,就可以实现点击弹框外阴影,不隐藏弹框&lt;
发表于:2023-11-28 浏览:1194 TAG:
【AntDesignPro】Ant Design Pro学习记录—ModalForm的使用(四)
一、 ModalForm自定义footer按钮参考官网,Modal弹框是可以自定义按钮的,原想着ModalForm的modalprops可以设置自定义footer,结果设置一直不生效,最终还是使用Modal嵌套了ProForm实现了功能,在此记录一下。ant design pro使用的V5版本。1、Modal自定义footer参考官网https://ant-design.antgroup.com/components/modal-cn?from=msidevs.net#components-mo
发表于:2024-02-20 浏览:363 TAG:
【AntDesignPro】Ant Design Pro学习记录—ProTable的使用(三)
一、 自定义检索条件部分列表页需要做一些简单的数据汇总统计,并能够跟随检索条件自动变化,protable自带的功能没有找到对应的实现方法,最后决定自己来实现这个功能。1、关闭ProTable自带检索功能search={false}2、自定义检索表单在ProTable上方加入自定义表单&lt;Card&nbsp;bordered={false}&nbsp;style={{&nbsp;marginBottom:&nbsp;15&nbsp;}}&gt; &nbsp;&nbsp;&nbsp;&nbsp;
发表于:2024-02-20 浏览:485 TAG:
【AntDesignPro】Ant Design Pro学习记录—自定义菜单选中
页面增删改查,打开子页面时,要让父页面菜单选中,参考官网给出的方案菜单的高级用法 - Ant Design Pro&nbsp;使用的V5版本,直接设置 parentKeys:[&#39;/product&#39;] 即可export&nbsp;default&nbsp;[ &nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;path:&nbsp;&#39;/product&#39;, &nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;不展示菜单 &nbsp;
发表于:2023-11-28 浏览:766 TAG: