【发布时间】:2017-07-16 09:34:56
【问题描述】:
我正在写一个画布,它在 angular2 的组件中绘制图像。
这里是 canvas.component.ts
export class BoardComponent implements OnInit, AfterViewInit, AfterViewChecked {
@ViewChild("visualization") visualization: ElementRef;
@ViewChild('img') img: ElementRef;
private context: CanvasRenderingContext2D;
private element: HTMLImageElement;
src: string;
width: number
height: number
constructor() {
this.src = 'https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png';
}
ngOnInit() {
this.width = 400;
this.height = 400;
}
ngAfterViewInit() {
this.context = this.visualization.nativeElement.getContext("2d");
this.element = this.img.nativeElement;
}
ngAfterViewChecked() {
this.context.clearRect(0, 0, this.width, this.height);
console.log('drawImage');
// this prints an image element with src I gave
console.log(this.element);
this.context.drawImage(this.element, 0, 0, this.width, this.height);
}
}
这是模板
<img #img src="{{src}}" style='display: none;' />
<canvas #visualization width="{{width}}" height="{{height}}"></canvas>`
看起来图像已经加载,但我的画布仍然是空的。
我发现了很多类似的问题,但没有一个使用 angular2。
例如,drawImage() not working 的回答是,您应该等到图像加载完毕。
但我不知道如何以角度方式检查这种情况。
有什么建议吗?
谢谢。
编辑
我发现可能是因为我渲染到画布上时图片没有加载。
我添加以下代码并调整页面大小,画布确实出现了。
@HostListener('window:resize')
resize() {
this.render();
}
render() {
this.context.clearRect(0, 0, this.width, this.height);
this.context.drawImage(this.element, 0, 0, this.width, this.height);
}
如果是这个原因,问题就变了,向 angular2 中的 html 元素添加事件监听器(如 img.onLoad)的正确方法是什么?
【问题讨论】:
-
我不知道 angular,但
this.img.nativeElement.onload不会做你想做的事吗?
标签: javascript html angular canvas