首页 > 解决方案 > HTML Canvas 不能与 React 一起使用,代码没有给出任何错误

问题描述

这是我正在尝试的代码,我正在尝试使用 react 在鼠标移动事件上绘制笔触。我是新手,所以我在互联网上看到了这种特殊的方法。请帮我解决一下这个。我错过了什么?

我什至尝试从 youtube 视频中复制粘贴确切的代码,但仍然无法正常工作

谢谢你

import React , { useRef, useEffect, useState } from 'react'
import ReactDOM from 'react-dom';


import './index.css'

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

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

  const finishDrawing = () => {
    contextRef.current.closePath()
    setIsDrawing(false)
  }
   const draw = (event) => {
     
     if (isDrawing) {
      contextRef.current.lineTo(event.offsetX, event.offsetY);
      contextRef.current.stroke();
      
    }
     
   }
    
  
    useEffect(() => {
    const board = boardRef.current
    board.width = window.innerWidth;
    board.height = window.innerHeight;
    const context = board.getContext('2d')
    
    context.scale(2, 2);
    context.lineCap = "round" ;
    context.lineJoin = "round" ; 
    context.lineWidth = 5;
    context.strokeStyle = "black"

    contextRef.current = context
  }, [])
 
    return (
        <canvas id="whiteboard" ref={boardRef}  onMouseDown={startDrawing} onMouseUp={finishDrawing} onMouseMove={draw}></canvas>
    )
}
ReactDOM.render(<App/>,document.getElementById('root'))

标签: reactjs

解决方案


e.offsetX表示undefined您需要使用的值e.nativeEvent.offsetX

同理e.offsetY,你需要使用e.nativeEvent.offsetY

这是代码片段


推荐阅读