【问题标题】:Getting dotted line on html Canvas在 html Canvas 上获取虚线
【发布时间】: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;

如何使用数组实现获得平滑线。

【问题讨论】:

标签: reactjs html5-canvas


【解决方案1】:

在您绘制线条的循环中,您无需在每次迭代时调用 moveTo。每次调用 lineTo() 都会自动添加到当前子路径中,这意味着所有的行都会被一起描边或填充。

您需要将 beginPath 拉出循环,删除 moveTo 调用并将笔画移出循环以提高效率。

 ctx.beginPath();
 for (let i = 0; i < strokes.length; i++) {

      //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.stroke();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-21
    • 1970-01-01
    • 2010-10-14
    • 2011-06-02
    • 1970-01-01
    • 1970-01-01
    • 2017-01-22
    相关资源
    最近更新 更多