Javascript HTML5画布撤消和重做反应

Javascript HTML5画布撤消和重做反应,javascript,html,reactjs,html5-canvas,Javascript,Html,Reactjs,Html5 Canvas,在使用画布在React上创建笔工具后,如何在每个鼠标绘制事件上实现撤消和重做。我一直在谷歌上搜索答案,但还没有找到一个明确的方法 我的密码在下面 function App(props) { const canvasRef = useRef(null); const contextRef = useRef(null); const [isDrawing, setIsDrawing] = useState(false); useEffect(() => {

在使用画布在React上创建笔工具后,如何在每个鼠标绘制事件上实现撤消和重做。我一直在谷歌上搜索答案,但还没有找到一个明确的方法

我的密码在下面

function App(props) {
    const canvasRef = useRef(null);
    const contextRef = useRef(null);
    const [isDrawing, setIsDrawing] = useState(false);

    useEffect(() => {
        const canvas = canvasRef.current;
        canvas.width = window.innerWidth * 2;
        canvas.height = window.innerHeight * 2;
        canvas.style.width = `${window.innerWidth}px`;
        canvas.style.height = `${window.innerHeight}px`;

        const context = canvas.getContext('2d');
        context.scale(2, 2);
        context.lineCap = 'round';
        context.strokeStyle = 'black';
        context.lineWidth = 5;
        contextRef.current = context;
    }, []);

    const startDrawing = ({ nativeEvent }) => {
        const { offsetX, offsetY } = nativeEvent;
        contextRef.current.beginPath();
        contextRef.current.moveTo(offsetX, offsetY);
        setIsDrawing(true);
    };

    const finishDrawing = () => {
        contextRef.current.closePath();
        setIsDrawing(false);
    };

    const draw = ({ nativeEvent }) => {
        if (!isDrawing) {
            return;
        }
        const { offsetX, offsetY } = nativeEvent;
        contextRef.current.lineTo(offsetX, offsetY);
        contextRef.current.stroke();
    };

    return <canvas onMouseDown={startDrawing} onMouseUp={finishDrawing} onMouseMove={draw} ref={canvasRef} />;
   
}
功能应用程序(道具){
const canvasRef=useRef(null);
const contextRef=useRef(null);
常量[isDrawing,setIsDrawing]=useState(false);
useffect(()=>{
const canvas=canvasRef.current;
canvas.width=window.innerWidth*2;
canvas.height=window.innerHeight*2;
canvas.style.width=`${window.innerWidth}px`;
canvas.style.height=`${window.innerHeight}px`;
const context=canvas.getContext('2d');
背景。量表(2,2);
context.lineCap='round';
context.strokeStyle='black';
context.lineWidth=5;
contextRef.current=上下文;
}, []);
常量startDrawing=({nativeEvent})=>{
const{offsetX,offsetY}=nativeEvent;
contextRef.current.beginPath();
contextRef.current.moveTo(offsetX,offsetY);
setIsDrawing(真);
};
const finishDrawing=()=>{
contextRef.current.closePath();
setIsDrawing(假);
};
常量绘制=({nativeEvent})=>{
如果(!isDrawing){
返回;
}
const{offsetX,offsetY}=nativeEvent;
contextRef.current.lineTo(offsetX,offsetY);
contextRef.current.stroke();
};
返回;
}