Angular-调整大小时画布未重新绘制形状
创始人
2024-10-21 03:30:44
0

问题描述: 当使用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; private resizeSubscription$: Subscription;

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);

} }

相关内容

热门资讯

截至目前!朋朋政和软件辅助器!... 截至目前!朋朋政和软件辅助器!一直有挂辅助器(真是有挂)-哔哩哔哩所有人都在同一条线上,像星星一样排...
相较于以往!手机透视辅助器ap... 相较于以往!手机透视辅助器app!确实存在有辅助神器(有挂助手)-哔哩哔哩1、上手简单,内置详细流程...
备受关注的!同城乐吧乐享版51... 备受关注的!同城乐吧乐享版510k辅助!竟然是真的辅助下载(有挂分析)-哔哩哔哩1、同城乐吧乐享版5...
目前!乐乐休闲游戏辅助!一贯真... 目前!乐乐休闲游戏辅助!一贯真的是有辅助工具(真实有挂)-哔哩哔哩1、首先打开乐乐休闲游戏辅助辅助器...
来临!微信多乐小程序游戏破解器... 来临!微信多乐小程序游戏破解器!一贯是有辅助平台(确实有挂)-哔哩哔哩1、超多福利:超高返利,海量正...
近年来!闲逸有没有辅助软件功能... 近年来!闲逸有没有辅助软件功能!好像存在有辅助神器(有挂教程)-哔哩哔哩该软件可以轻松地帮助玩家将闲...
截至目前!博雅红河西元!一直真... 截至目前!博雅红河西元!一直真的有辅助神器(确实有挂)-哔哩哔哩1、在博雅红河西元插件功能辅助器技巧...
长期以来!约战丹东游戏辅助器!... 长期以来!约战丹东游戏辅助器!一贯真的有辅助平台(有挂详情)-哔哩哔哩1、许多玩家不知道约战丹东游戏...
在玩家背景下!人海大厅脚本!竟... 在玩家背景下!人海大厅脚本!竟然有挂辅助安装(有挂分享)-哔哩哔哩1、首先打开人海大厅脚本辅助器下载...
据了解!宁德钓螃蟹有没有挂!一... 据了解!宁德钓螃蟹有没有挂!一贯是有辅助下载(有挂讲解)-哔哩哔哩所有人都在同一条线上,像星星一样排...