H5图片上传与裁剪(头像)


背景
最近接到的需求中H5头像上传和实现基本的图片裁剪,这也是比较常见且典型的场景。

思路

1. 调起移动端相机拍照或相册功能;

2. 选择图片后,将选中的图片放入画布;

3. 因为基于react框架开发,所以使用了第三方插件react- cropper

代码实现

1. 封装react组件

import { useState } from "react";
import HooksCropperModal from "./HooksCropperModal";
import styles from "./index.module.less";

const MAX_FILE_SIZE = 5 * 1024 * 1024; // 文件最大限制为5M

const Avator = () => {
  const [hooksModalVisible, setHooksModalVisible] = useState(false); // 裁剪图片
  const [hooksModalFile, setHooksModalFile] = useState(null); // 选取的img文件
  const [hooksResultImgUrl, setHooksResultImgUrl] = useState(null); // 裁剪后的img

  const handleHooksFileChange = (e) => {
    const file = e.target.files[0];

    if (file) {
      if (file.size <= MAX_FILE_SIZE) {
        setHooksModalFile(file);
        setHooksModalVisible(true)

猜你喜欢

转载自blog.csdn.net/gkf6104/article/details/129358920