问题描述: 当使用Angular创建一个canvas元素并在其上绘制形状时,当调整窗口大小时,形状不会随着画布的大小而重新绘制。
为了解决这个问题,可以在窗口大小更改时使用Angular的Renderer2对象手动重新设置画布的大小,并且清空画布并重新绘制形状。
示例代码:
HTML:
TS: import { Component, ElementRef, ViewChild, Renderer2, OnInit, OnDestroy } from '@angular/core';
@Component({
selector: 'app-canvas-resize',
templateUrl: './canvas-resize.component.html',
styleUrls: ['./canvas-resize.component.css']
})
export class CanvasResizeComponent implements OnInit, OnDestroy {
@ViewChild('canvas') canvasRef: ElementRef;
private ctx: CanvasRenderingContext2D;
private resizeObservable$: Observable
constructor(private renderer: Renderer2) { }
ngOnInit() { const canvas: HTMLCanvasElement = this.canvasRef.nativeElement; canvas.width = window.innerWidth; canvas.height = window.innerHeight;
this.ctx = canvas.getContext('2d');
this.ctx.fillStyle = '#FF0000';
this.ctx.fillRect(10, 10, 50, 50);
this.resizeObservable$ = fromEvent(window, 'resize');
this.resizeSubscription$ = this.resizeObservable$.pipe(
debounceTime(200) // debounceTime是为了减少resize事件的频率
).subscribe(() => this.resizeCanvas());
}
ngOnDestroy() { this.resizeSubscription$.unsubscribe(); }
resizeCanvas(): void { const canvas: HTMLCanvasElement = this.canvasRef.nativeElement; this.renderer.setProperty(canvas, 'width', window.innerWidth); this.renderer.setProperty(canvas, 'height', window.innerHeight);
this.ctx.clearRect(0, 0, canvas.width, canvas.height); // 清除画布
this.ctx.fillStyle = '#FF0000';
this.ctx.fillRect(10, 10, 50, 50);
} }