【问题标题】:Observer canvas background src dinamically generated观察者画布背景src动态生成
【发布时间】:2021-12-27 22:41:20
【问题描述】:

首次加载画布时,background.src 为空。 在对话框中(对话框在第二个组件中)我上传IMG但成功后background.src仍然是空的,我需要刷新应用程序才能获得background.src = this.src;。

上传后如何设置observable更改background.src再次调用this.src = this.srcService.getImgURL(this.id) // returned string 'https://something.com/image/1234',因为画布已经加载?

或者也许是其他东西而不是可观察的?

我尝试在后台 src 上设置超时时间为 1 秒,这是可行的,但 setTimeout 不是在我们的应用程序中使用的选项。

不能使用background.onload = () => {...},因为在此之前我需要 src。

谢谢

第一个组件

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

第二部分 第二个组件是我选择并上传图片的对话框

 export class SecondComponent implements {
       constructor( @Inject(MAT_DIALOG_DATA) public data: IInterface,
                    public dialogRef: MatDialogRef<SettingsComponent>) 
    ( ... )
      close() {
         this.dialogRef.close(null);
       }
    }

【问题讨论】:

  • 我不确定,但background.src 是异步的,你无法绕过这个事实。所以你可能需要一个fromEvent(background, "load") observable 来等到源被加载,然后再继续SecondComponent。这类似于background.addEventListener("load", () =&gt; {})background.onload = () =&gt; {}
  • 嗨,我会试试这个想法... thnx

标签: javascript angular html5-canvas


【解决方案1】:

图像加载后,您还应该使用 2d 上下文将背景设置为画布:

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

【讨论】:

  • 嗨@Octavian Mărculescu thnx 重播。我已经使用 onLoad,但问题是,画布在对话框(我上传 img 的地方)加载,并且在上传新的 img 后,background.src 没有改变....我也尝试 .clearRect() 但同样的情况
  • 好的,所以问题是在您在对话框中选择另一个图像后背景不会更新,对吧?因为这段代码在ngAfterViewInit 中,只被调用一次。
  • 是的,这就是问题
  • 如何从对话框中获取图像 URL?你的方法是什么?您能否在问题内容中包含SrcService 的实现?
猜你喜欢
  • 2016-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-13
  • 1970-01-01
  • 2023-02-05
  • 2021-10-19
相关资源
最近更新 更多