下面是一个使用Angular在鼠标事件上使用画布绘制多个矩形的示例代码:
首先,我们需要在app.module.ts
中导入NgModule
和BrowserModule
模块,并将其添加到imports
数组中:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
然后,在app.component.ts
中,我们需要导入Component
、ViewChild
和ElementRef
模块,并定义一个CanvasRenderingContext2D
变量来操作画布:
import { Component, ViewChild, ElementRef } from '@angular/core';
@Component({
selector: 'app-root',
template: `
`,
styles: []
})
export class AppComponent {
@ViewChild('canvas', { static: true }) canvas: ElementRef;
private ctx: CanvasRenderingContext2D;
private isDrawing: boolean = false;
private startX: number;
private startY: number;
ngAfterViewInit() {
this.ctx = this.canvas.nativeElement.getContext('2d');
}
onMouseDown(event: MouseEvent) {
this.isDrawing = true;
this.startX = event.offsetX;
this.startY = event.offsetY;
}
onMouseMove(event: MouseEvent) {
if (!this.isDrawing) return;
this.ctx.clearRect(0, 0, this.canvas.nativeElement.width, this.canvas.nativeElement.height);
this.ctx.beginPath();
this.ctx.rect(this.startX, this.startY, event.offsetX - this.startX, event.offsetY - this.startY);
this.ctx.stroke();
}
onMouseUp(event: MouseEvent) {
if (!this.isDrawing) return;
this.isDrawing = false;
this.ctx.rect(this.startX, this.startY, event.offsetX - this.startX, event.offsetY - this.startY);
this.ctx.fill();
}
}
在上面的代码中,我们在app.component.ts
中定义了一个名为canvas
的ViewChild
来获取画布元素,并使用ElementRef
来获取画布的上下文。
在onMouseDown
方法中,我们将isDrawing
设置为true
,并记录鼠标点击时的起始坐标。
在onMouseMove
方法中,我们首先清空画布,然后使用rect
方法绘制一个矩形,该矩形的起始坐标为鼠标点击时的坐标,而结束坐标为当前鼠标移动的坐标。
在onMouseUp
方法中,我们将isDrawing
设置为false
,然后使用rect
方法绘制最终的矩形,并使用fill
方法填充矩形。
最后,在app.component.html
中添加
标签以显示组件:
Angular Canvas Example
现在,当你在画布上按下鼠标并移动时,你将能够绘制多个矩形。