[英]Why my canvas drawImage not showing up in angular2 component
我正在編寫一個在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()不能正常工作的答案是您應該等待圖像加載完畢。
但是我不知道如何以角度的方式檢查這種情況。
有什么建議嗎?
謝謝。
我發現可能是因為在將圖像渲染到畫布時未加載圖像。
我添加以下代碼並調整頁面大小,畫布確實顯示出來。
@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);
}
如果是這個原因,問題就會改變,將事件偵聽器(如img.onLoad)添加到angular2中的html元素的正確方法是什么?
在這里,我修改了您的代碼以使其工作。
的HTML
<img #img src="{{src}}" (load)="afterLoading()" style='display: none;' />
<canvas #visualization width={{imgWidth}} height={{imgHeight}} "></canvas>
打字稿
export class BoardComponent implements implements AfterViewInit {
@ViewChild("visualization") visualization: ElementRef;
@ViewChild('img') img: ElementRef;
private context: CanvasRenderingContext2D;
private element: HTMLImageElement;
src: string;
imgWidth: number;
imgHeight: number;
constructor() {
this.imgWidth = 400;
this.imgHeight = 400;
this.src = 'https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png';
}
ngAfterViewInit() {
this.context = this.visualization.nativeElement.getContext("2d");
this.element = this.img.nativeElement;
}
afterLoading(){
this.context.clearRect(0, 0, this.imgWidth, this.imgHeight);
console.log('drawImage');
// this prints an image element with src I gave
console.log(this.element);
this.context.drawImage(this.element, 0, 0, this.imgWidth, this.imgHeight);
}
}
這是工作中的演示
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.