canvas

import React, { memo, useEffect, useState, useRef } from 'react';
import { Button, message, Spin, Row, Col, Table, Radio, Upload } from 'antd';
// 图片水平垂直居中

const Ocr_ = () => {
  const [isDraw, setIsDraw] = useState<boolean>(false);
  const [location, setLocation] = useState<any>([]);
  const canvasRef = useRef<HTMLCanvasElement>(null!);
  const mouseEvent = (e: React.MouseEvent) => {
    const ctx = canvasRef.current.getContext('2d')!;
    if (e.type === 'mousedown') {
      setIsDraw(true);
    }
    if (e.type === 'mouseup') {
      setIsDraw(false);
    }
    if (e.type === 'mousemove' && isDraw) {
      const { left, top } = canvasRef.current.getBoundingClientRect();
      let width = e.pageX - left;
      let height = e.pageY - top;
      location.push([width, height]);
      setLocation(location);
      let rectLeft = location[0][0];
      let rectTop = location[0][1];
      let preWidth = 0;
      let preHeight = 0;
      const len = location.length;
      if (len > 1) {
        const len = location.length;
        preWidth = location[len - 2][0] - rectLeft;
        preHeight = location[len - 2][1] - rectTop;
      }
      let curWidth = location[len - 1][0] - rectLeft;
      let curHeight = location[len - 1][1] - rectTop;
      ctx.beginPath();
      ctx.lineWidth = 2;
      ctx.clearRect(rectLeft, rectTop, preWidth, preHeight);
      ctx.fillStyle = 'rgba(52, 14, 219, 0.1)';
      ctx.fillRect(rectLeft, rectTop, curWidth, curHeight);
    }
    if (e.type === 'mouseleave') {
      setIsDraw(false);
    }
  };

  const clearCanvas = () => {
    const { height } = canvasRef.current;
    canvasRef.current.height = height;
    setLocation([]);
  };
  return (
    <>
      <div style={{ fontWeight: 400, fontSize: 16 }}>
        <canvas
          ref={canvasRef}
          width={800}
          height={400}
          style={{ background: '#f3f3f3', cursor: 'crosshair' }}
          onMouseDown={mouseEvent}
          onMouseMove={mouseEvent}
          onMouseUp={mouseEvent}
          onMouseLeave={mouseEvent}
        ></canvas>
      </div>
      <Button onClick={clearCanvas}>cancle</Button>
    </>
  );
};

export const Ocr = memo(Ocr_);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值