Angular (Javascript) 如何控制mousemove事件的速度?
Angular (Javascript) how to control the speed of mousemove event?
我正在尝试使用鼠标移动事件
在 canvas 上绘图
你可以在这个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 次拖动绘制中的矩形?
编辑:我希望能够画出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));
解释:
你的想法是对的,问题是你发送到 clearRect
的区域实际上并不包括边界。根据 documentation(强调我的),
The CanvasRenderingContext2D.strokeRect() method of the Canvas 2D API
draws a rectangle that is stroked (outlined) according to the current
strokeStyle and other context settings.
因此,要清除边框,您实际上需要在尝试清除边框时考虑边框宽度。
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);
我正在尝试使用鼠标移动事件
在 canvas 上绘图你可以在这个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 次拖动绘制中的矩形?
编辑:我希望能够画出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));
解释:
你的想法是对的,问题是你发送到 clearRect
的区域实际上并不包括边界。根据 documentation(强调我的),
The CanvasRenderingContext2D.strokeRect() method of the Canvas 2D API draws a rectangle that is stroked (outlined) according to the current strokeStyle and other context settings.
因此,要清除边框,您实际上需要在尝试清除边框时考虑边框宽度。
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);