0

我正在尝试使用鼠标移动事件在画布上绘图

你可以看到这个闪电战的工作演示 我在鼠标移动时调用这个函数来绘制一个矩形

 updateDraw(e: MouseEvent) {

    this.previousCoordinates = this.currentCoordinates;
    this.currentCoordinates = HelloComponent.getCoordinatesOnCanvas(this.canvas.nativeElement, e);
    if (this.drawingMode) {
      HelloComponent.createShape(this.shapes, this.ctx, this.startCoordinates,
        this.currentCoordinates, this.previousCoordinates, true);
      this.endCoordinates = this.currentCoordinates;
    }
  }

问题是,如果我将鼠标移动得太快,我会得到多个矩形,(我假设清除矩形不起作用,因为鼠标移动太快)我怎样才能避免这种情况在 1 次拖动中应该只有 1 个矩形?

在此处输入图像描述

编辑:我希望能够绘制超过 1 个矩形,这里我正在跟踪和清除以前的坐标

  private static createShape(shape: Shapes, context: CanvasRenderingContext2D,
    start: Coordinates, end: Coordinates, prev: Coordinates,
    dotted: boolean) {

    context.clearRect(start.x, start.y, (prev.x - start.x), (prev.y - start.y));
4

1 回答 1

1

StackBlitz

解释:

你有正确的想法,问题是你发送到的区域clearRect实际上并不包括边界。根据文档(强调我的),

Canvas 2D API 的 CanvasRenderingContext2D.strokeRect() 方法根据当前的 strokeStyle 和其他上下文设置绘制一个被描边(轮廓)的矩形。

因此,要清除边框,您实际上需要在尝试清除边框时考虑边框宽度。

const borderWidth = 1;
const x = Math.min(start.x, prev.x) - borderWidth;
const y = Math.min(start.y, prev.y) - borderWidth;
const width = Math.abs(start.x - prev.x) + (2 * borderWidth);
const height = Math.abs(start.y - prev.y) + (2 * borderWidth);

context.clearRect(x, y, width, height);
于 2019-05-30T15:36:36.013 回答