0

I am making an app, where I'm showing the image on the canvas, But the image src is coming from the parent page.

Everything is working file, but when I'm changing the imageSrc on button click, It's showing a blank canvas. After that When I'm clicking outside of the div new image showed fine.

preview.page.html

<ion-content no-padding>
  <img #img src="{{imgSrc}}" style='display: none;' />
  <canvas #imageCanvas (touchstart)="startDrawing($event)"></canvas>
</ion-content>

and preview.page.ts

export class PreviewBoxPage implements OnInit, AfterViewInit, AfterViewChecked {
  @ViewChild('previewImg', {static: false}) waterMarkImage: ElementRef;
  @ViewChild('imageCanvas', {static: false}) canvas: ElementRef;
  @ViewChild('img', {static: false}) img: ElementRef;

  @ViewChild(Platform , {static: false}) content: Platform;
  canvasElement: HTMLCanvasElement;
  private element: HTMLImageElement;

  private ctx: CanvasRenderingContext2D;

  @Input()
  imgSrc;    

  ngAfterViewInit() {
    this.canvasElement = this.canvas.nativeElement;
    this.element = this.img.nativeElement;

    this.canvasElement.width =  this.plt.width();
    this.canvasElement.height = 270;

    this.ctx = this.canvasElement.getContext('2d');
  }

  ngAfterViewChecked() {

    this.ctx.clearRect(0, 0, this.canvasElement.width, this.canvasElement.height);
    this.ctx.drawImage(this.element, 0, 0);
  }}

Someone, please explain to me this. It's been a week, I couldn't find a solution.

Rupesh
  • 850
  • 2
  • 13
  • 30
  • Im not sure but it might happen as you set `this.element` only once within `ngAfterViewInit`, which is not called when you update your Input `imgSrc` from outside the component. You could try updating `this.element` and drawing to the canvas only when the input is changed (see https://stackoverflow.com/questions/38571812/how-to-detect-when-an-input-value-changes-in-angular) – Howäms Jun 05 '20 at 08:48
  • @Howäms I have tried that but didn't work – Rupesh Jun 05 '20 at 17:52

1 Answers1

0

The only issue was that the image was coming from the online website. It was taking some time on loading. So I just add the (load) event

  <img #img [src]="imgSrc" (load)="onImageLoad($event)" style='display: none;' />

and then set that function in the page.ts

onImageLoad(event) {
}

it is working fine now :)

Rupesh
  • 850
  • 2
  • 13
  • 30