我正在尝试使用鼠标移动事件在画布上绘画
您可以在此blitzy上看到有效的演示 我在移动鼠标以绘制矩形时调用此函数
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抽奖?
编辑:我希望能够绘制多个矩形,这里我正在跟踪和清除以前的坐标
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));
答案 0 :(得分:1)
说明:
您有一个正确的想法,问题是您要发送到clearRect
的区域实际上没有边界。根据{{3}}(强调我的意思)
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);