angular - 如何使用 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
}
由于每个组件都有自己的画布,我的期望是通过访问它们的方式获得两个不同的画布元素。然而,似乎我总是得到当前显示的画布,并且第一个形状被第二个覆盖。当滑动到另一个画布时,它只是空的默认画布。
任何有关如何访问“隐藏”画布的线索将不胜感激,并得到正确的滑块将不胜感激。
解决方案
根据浏览器标准,具有多个具有相同名称的 id 是有效的,但是当您查询 DOM 时它的工作方式不同,它将始终返回第一次出现的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
}
推荐阅读
- typescript - 如何基于 while 循环创建可观察对象?
- python - 在 sns.heatmap(...) 中使用 square=True 时增加图形大小
- python - 用一行代码绘制重新采样的时间序列面积图?
- javascript - Sequelize 自定义验证 - 无法访问实体中的所有字段
- python - Matplotlib 中补丁的平滑颜色变化动画
- typescript - 在 Typescript 中使用数组初始化 Map:new Map([[k1, v1], [k2, v2]])
- java - 移除模拟器上的 Google Play 服务
- ruby-on-rails - Ruby 中的 JSON 反序列化
- jupyter-notebook - 为什么用 xeus-cling 激活 Jupyter 失败
- autohotkey - 如何有“输入”(或者它是上下文?)依赖热字符串/热键?