如何使用 Ionics 离子幻灯片在 HTML5 画布之间切换?
How do I switch between HTML5 canvases using Ionics ion-slides?
我正在编写一个应用程序,我想在其中显示根据我当前所在的幻灯片在 HTML5 canvas 上绘制的不同形状。
所以当应用程序加载时,我想初始化 2 张幻灯片,一张是三角形,一张是正方形,并且能够使用 Ionics 离子幻灯片在它们之间滑动。
所以在另一个组件中,我使用我的 canvas 组件,如下所示创建三个选项卡:
<ion-slides id='slides'>
<ion-slide *ngFor='let index of [0,1]'>
<customCanvas [index]='index'></customCanvas>
</ion-slide>
</ion-slides>
我的customCanvas.component.html只包含一个canvas像:
<canvas id="canvas" width="300px" height="300px"></canvas>
并且 customCanvas.component.ts 初始化 canvas 在:
ngOnInit() {
this.canvas = <HTMLCanvasElement>document.getElementById('canvas');
var context = this.canvas.getContext("2d");
//use the context to draw either a triangle/square
}
由于每个组件都有一个自己的 canvas,我的期望是我会通过访问它们的方式获得两个不同的 canvas 元素。
然而,我似乎总是得到当前显示的 canvas 并且第一个形状被第二个覆盖。
当滑动到另一个canvas时,就是空的默认canvas.
任何有关如何访问 "hidden" canvas 的线索都将不胜感激,并将不胜感激。
根据浏览器标准,具有多个具有相同名称的 ID 是有效的,但是当您查询 DOM 时,它不会以相同的方式工作,它总是 return 第一次出现 ID
。这里的问题是您正在使用 canvas
id 查询文档。在这里您可以考虑将 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
}
我正在编写一个应用程序,我想在其中显示根据我当前所在的幻灯片在 HTML5 canvas 上绘制的不同形状。
所以当应用程序加载时,我想初始化 2 张幻灯片,一张是三角形,一张是正方形,并且能够使用 Ionics 离子幻灯片在它们之间滑动。
所以在另一个组件中,我使用我的 canvas 组件,如下所示创建三个选项卡:
<ion-slides id='slides'>
<ion-slide *ngFor='let index of [0,1]'>
<customCanvas [index]='index'></customCanvas>
</ion-slide>
</ion-slides>
我的customCanvas.component.html只包含一个canvas像:
<canvas id="canvas" width="300px" height="300px"></canvas>
并且 customCanvas.component.ts 初始化 canvas 在:
ngOnInit() {
this.canvas = <HTMLCanvasElement>document.getElementById('canvas');
var context = this.canvas.getContext("2d");
//use the context to draw either a triangle/square
}
由于每个组件都有一个自己的 canvas,我的期望是我会通过访问它们的方式获得两个不同的 canvas 元素。 然而,我似乎总是得到当前显示的 canvas 并且第一个形状被第二个覆盖。 当滑动到另一个canvas时,就是空的默认canvas.
任何有关如何访问 "hidden" canvas 的线索都将不胜感激,并将不胜感激。
根据浏览器标准,具有多个具有相同名称的 ID 是有效的,但是当您查询 DOM 时,它不会以相同的方式工作,它总是 return 第一次出现 ID
。这里的问题是您正在使用 canvas
id 查询文档。在这里您可以考虑将 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
}