首页 > 解决方案 > 更改图像 src 后画布上的 Ionic 4 drawImage

问题描述

我正在制作一个应用程序,我在画布上显示图像,但图像 src 来自父页面。

一切都是工作文件,但是当我在按钮单击时更改 imageSrc 时,它显示的是空白画布。之后,当我在 div 外部单击时,新图像显示正常。

preview.page.html

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

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);
  }}

有人,请给我解释一下。已经一个星期了,我找不到解决方案。

标签: javascriptangularcanvasionic4

解决方案


唯一的问题是图像来自在线网站。加载需要一些时间。所以我只是添加(load) 事件

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

然后在 page.ts 中设置该函数

onImageLoad(event) {
}

现在工作正常:)


推荐阅读