首页 > 解决方案 > 如何使用 Ionics 离子幻灯片在 HTML5 画布之间切换?

问题描述

我正在编写一个应用程序,在该应用程序中,我想根据我当前使用的幻灯片显示在 HTML5 画布上绘制的不同形状。

因此,当应用程序加载时,我想初始化两张幻灯片,一张是三角形,一张是正方形,并且能够使用 Ionics 离子幻灯片在它们之间滑动。

因此,在另一个组件中,我使用如下所示的画布组件来创建三个选项卡:

 <ion-slides id='slides'>
    <ion-slide *ngFor='let index of [0,1]'>
      <customCanvas [index]='index'></customCanvas>
    </ion-slide>
  </ion-slides>

我的 customCanvas.component.html 只包含一个画布,如:

<canvas id="canvas" width="300px" height="300px"></canvas>

并且 customCanvas.component.ts 将画布初始化为:

  ngOnInit() {
    this.canvas = <HTMLCanvasElement>document.getElementById('canvas');
    var context = this.canvas.getContext("2d");

    //use the context to draw either a triangle/square
  }

由于每个组件都有自己的画布,我的期望是通过访问它们的方式获得两个不同的画布元素。然而,似乎我总是得到当前显示的画布,并且第一个形状被第二个覆盖。当滑动到另一个画布时,它只是空的默认画布。

任何有关如何访问“隐藏”画布的线索将不胜感激,并得到正确的滑块将不胜感激。

标签: angularhtmlionic-frameworkhtml5-canvasionic4

解决方案


根据浏览器标准,具有多个具有相同名称的 id 是有效的,但是当您查询 DOM 时它的工作方式不同,它将始终返回第一次出现的ID. 这里的问题是您正在使用canvasid 查询文档。在这里你可以考虑换成id选择class器。

然后在查询 DOM 时,使用this.elementRef.nativeElement. 在进行任何类型的 DOM 操作之前,还要使用ngAfterViewInit生命周期来确保组件 DOM 存在。

constructor(private elementRef: ElementRef) {}

ngAfterViewInit() {
    // You could also use Renderer2 API for SSR and WebWorker support
    this.canvas = this.elementRef.nativeElement.getElementByClassName('canvas');
    var context = this.canvas.getContext("2d");

    //use the context to draw either a triangle/square
}

推荐阅读