when first-time load canvas, background.src is empty.
In dialog (dialog is in the second component) I upload IMG but after the success, background.src is still empty, I need to refresh app to get background.src = this.src;.
How to set observable to change background.src after upload to call again this.src = this.srcService.getImgURL(this.id) // returned string 'https://something.com/image/1234', because canvas is already loaded?
Or maybe something else instead of observable?
I tried to set timeout with 1 second on background src and this is working, but setTimeout is not an option to use in our app.
Can not use background.onload = () => {...} because I need src before this.
Thnx
First component
export class FirstComponent implements AfterViewInit {
@ViewChild('canvas', { static: true }) canvas: ElementRef<HTMLCanvasElement>;
ngAfterViewInit() {
this.src = this.srcService.getImgURL(this.id) // returned string 'https://something.com/image/1234'
const background = new Image();
background.src = this.src;
}
}
Second component The second component is a dialog where I choose and upload the image
export class SecondComponent implements {
constructor( @Inject(MAT_DIALOG_DATA) public data: IInterface,
public dialogRef: MatDialogRef<SettingsComponent>)
( ... )
close() {
this.dialogRef.close(null);
}
}
After the image loads, you should set the background to the canvas as well using the 2d context:
ngAfterViewInit() {
this.src = this.srcService.getImgURL(this.id);
const background = new Image();
background.src = this.src;
background.onload = () => {
const ctx = this.canvas.getContext("2d");
ctx.drawImage(background, 0, 0);
}
}