我正在使用React开发实时绘画应用程序。因此,这个想法是将鼠标事件存储在一个数组中(通过套接字传递),然后将其传递给draw函数。但是,当我快速移动鼠标时,我得到的是虚线而不是平滑线。如果我直接使用鼠标事件而不是数组进行绘制,则线条会很平滑。因此,我想问题出在将鼠标事件推入数组中。
这是我的输出:
以下是我的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;
如何使用数组实现获得一条平滑的线。
在绘制线条的循环中,不需要每次迭代都调用moveTo。每次调用lineTo()都会自动将其添加到当前子路径,这意味着所有的行都将被描边或填充在一起。
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); // Remove this line
ctx.lineTo(strokes[i].x - left, strokes[i].y - top + 32);
}
// Its also more efficient to call these once for the whole line
ctx.closePath();
ctx.stroke();