首页 > 解决方案 > 角度画布在调整大小时不刷新

问题描述

我有一个 Angular Canvas,我想根据窗口大小调整它的大小。我在我的组件中这样做了:

@HostListener('window:resize', ['$event'])
onResize(event) {
    this.canvaHeight = window.innerHeight * 0.91;
    this.canvaWidth = window.innerWidth  * 0.75;
}

在我的 html 中:

<canvas id="canvas" #canvas width="{{ canvaWidth }}" height="{{ canvaHeight }}" (mousedown)="select($event)" (mousemove)="move($event)" (mouseup)="drop()"></canvas>

当我调整窗口大小时,画布大小会正确更改,但上面的所有内容都会消失。当我执行调用更新函数的操作时,它会重新出现。但是如果我在 onResize 函数中调用它,它就不会再次出现,我也不知道为什么。

@HostListener('window:resize', ['$event'])
onResize(event) {
    this.canvaHeight = window.innerHeight * 0.91;
    this.canvaWidth = window.innerWidth  * 0.75;
    this.update();
}

任何想法 ?我必须以某种方式刷新 DOM 吗?那怎么办呢?

编辑:如果我移动一个对象,即使它还没有重新出现,它也确实被移动了。

我还尝试了 Promise 和一些刷新 DOM 的方法,例如 ApplicationRef.tick() 和 ChangeDetectorRef.detectChanges() 但它不起作用

标签: htmlangulartypescripthtml5-canvas

解决方案


感谢 Blindman67,我找到了一种让它工作的方法:

@HostListener('window:resize')
onResize() {
    this.canvaHeight = Math.floor(window.innerHeight * 0.91);
    this.canvaWidth = Math.floor(window.innerWidth  * 0.75);
    this.canvas.nativeElement.height = this.canvaHeight;
    this.canvas.nativeElement.width = this.canvaWidth;
    this.update();
}

(我仍然需要存储其他东西的值)

(Math.floor 是为了更正浏览器的警告)


推荐阅读