reactjs - 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'))
解决方案
推荐阅读
- azure - Rancher / k8 / azure / Kubectl
- excel - Excel VBA 排序错误
- load-balancing - Envoy 需要管理员权限的原因是什么,可以避免吗?
- android - 填充或边距仅在左侧和右侧,但不在顶部和底部
- javascript - 为什么监听器不工作?
- python - 来自多个地方的 Python 日志记录调用模块
- c# - 你推荐哪个系列?
- java - Java:递归模式搜索文件(具有相对路径)以作为变量传递
- powershell - 使用 Powershell 查找 SSIS 包中的存储过程
- java - 如何将数据放入 JasperReports 中的表格中?