【发布时间】:2020-06-05 12:52:35
【问题描述】:
我正在使用 React 开发一个实时绘图应用程序。因此,想法是将鼠标事件存储在一个数组中(通过套接字传递)并将其传递给绘图函数。但是,当我快速移动鼠标时,我得到的是虚线而不是平滑线。如果我直接使用鼠标事件而不是数组进行绘制,我会得到一条平滑的线。所以我想问题在于将鼠标事件推送到数组中。
这是我的输出:
以下是我的 PaintCanvas 组件
function PaintCanvas(props) {
let ctx;
const canvasRef = useRef("");
const [isDrawing, changeIsDrawing] = useState(false);
let strokes = [];
const mouseDownFunction = e => {
changeIsDrawing(true);
if (ctx) {
wrapperForDraw(e);
}
};
const mouseUpFunction = e => {
if (ctx) {
ctx.beginPath();
}
changeIsDrawing(false);
};
const mouseMoveFunction = e => {
if (ctx) {
wrapperForDraw(e);
}
};
const wrapperForDraw = e => {
if (!isDrawing) return;
strokes.push({
x: e.clientX,
y: e.clientY
});
drawFunction(strokes);
};
const drawFunction = strokes => {
let { top, left } = canvasRef.current.getBoundingClientRect();
if (!isDrawing) return;
ctx.lineWidth = 3;
ctx.lineCap = "round";
for (let i = 0; i < strokes.length; i++) {
ctx.beginPath();
//adding 32px to offset my custom mouse icon
ctx.moveTo(strokes[i].x - left, strokes[i].y - top + 32);
ctx.lineTo(strokes[i].x - left, strokes[i].y - top + 32);
ctx.closePath();
ctx.stroke();
}
};
useEffect(() => {
let canvas = canvasRef.current;
ctx = canvas.getContext("2d");
});
return (
<div>
<canvas
ref={canvasRef}
width="500px"
height="500px"
onMouseDown={mouseDownFunction}
onMouseUp={mouseUpFunction}
onMouseMove={mouseMoveFunction}
className={styles.canvasClass}
/>
</div>
);
}
export default PaintCanvas;
如何使用数组实现获得平滑线。
【问题讨论】:
-
这个库是否符合您的需求? npmjs.com/package/react-canvas-draw
-
@keikai 我不确定如何在使用提到的包时存储事件。无论如何,我想自己编写画布。
标签: reactjs html5-canvas