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_);
canvas
最新推荐文章于 2022-12-02 11:06:13 发布