我有一个angular2组件:
@Component({
selector: 'my-image',
template: `
<img #img src="{{src}}" style='display: none;' />
<canvas #canvas width="{{width}}" height="{{height}}"></canvas>`
})
export class ImageComponent implements AfterViewInit {
@ViewChild('canvas') canvas: ElementRef;
@ViewChild('img') img: ElementRef;
private ctx: CanvasRenderingContext2D;
private element: HTMLImageElement;
src: string;
width: number;
height: number;
constructor(canvas: ElementRef, img: ElementRef) {
this.width = window.innerWidth;
this.height = window.innerHeight;
this.src = 'https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png';
}
ngAfterViewInit() {
this.ctx = this.canvas.nativeElement.getContext('2d');
this.element = this.img.nativeElement;
}
@HostListener('window:resize')
resize() {
this.width = window.innerWidth;
this.height = window.innerHeight;
this.render();
}
clear() {
this.ctx.clearRect(0, 0, this.width, this.height);
}
render() {
this.clear();
this.ctx.drawImage(this.element, 0, 0, 400, 400);
}
}
所以一切都很好,但是,当我调整窗口大小时,调整大小回调会被命中并调用渲染。然后在画布上发生绑定,重置上下文,并留下空白画布。我最初的想法是在发生变化检测后再次调用渲染。这是正确的方法还是有更好的方法?
由于
答案 0 :(得分:0)
@rinukkusu答案是对的,谢谢!
也许尝试在
中调用render方法ngAfterViewChecked