(newbie question)
I am trying to make a custom component (MyCanvas) which draws a circle on a canvas.
On the Home page I want to provide a button which moves the circle.
Using a directive I can get the home page to draw the canvas, but the button doesn’t work.
On the other hand, if I use a provider (dependency injection) the button does something but the canvas is not shown.
MyCanvas.ts:
import {Component, Injectable, Input, ViewChild, ElementRef} from 'angular2/core';
@Injectable()
@Component({
selector: 'my-canvas',
template: `<canvas #theCanvas [attr.width]='width' [attr.height]='height'></canvas>`,
})
export class MyCanvas {
@ViewChild("theCanvas") theCanvas: ElementRef;
constructor() {
this.width = 200;
this.height = 100;
this.x = 20;
}
ngAfterViewInit() {
console.log("ngAfterViewInit");
this.context = this.theCanvas.nativeElement.getContext("2d");
this.redraw();
}
redraw(): void {
let context = this.context;
this.context.strokeStyle = 'black';
this.context.strokeRect(0, 0, this.width, this.height);
this.context.beginPath();
this.context.arc(this.x, 50, 5, 0, 2*Math.PI);
this.context.stroke();
}
move() : void {
this.x += 10;
this.redraw();
}
private context: CanvasRenderingContext2D;
private width: number;
private height: number;
private x: number;
}
home.html:
<ion-navbar *navbar>
<ion-title>
Home
</ion-title>
</ion-navbar>
<ion-content class="home">
<ion-card>
<ion-card-header>
Moving circle
</ion-card-header>
<ion-card-content>
<my-canvas></my-canvas>
<button (click)="move()">Move</button>
</ion-card-content>
</ion-card>
</ion-content>
Scenario 1 using directives
home.ts:
import {Page} from 'ionic-angular';
import {MyCanvas} from '../../MyCanvas';
@Page({
templateUrl: 'build/pages/home/home.html',
directives: [ MyCanvas ], // <------------
//providers: [ MyCanvas ]
})
export class HomePage {
move(): void {
this.myCanvas.move();
}
myCanvas: MyCanvas;
}
result:
- canvas is drawn (ngAfterViewInit() is called)
- button click -> in move() this.myCanvas is undefined
Scenario 2 using providers
home.ts:
import {Page} from 'ionic-angular';
import {MyCanvas} from '../../MyCanvas';
@Page({
templateUrl: 'build/pages/home/home.html',
//directives: [ MyCanvas ],
providers: [ MyCanvas ] // <------------
})
export class HomePage {
constructor( myCanvas: MyCanvas) { // <------------
this.myCanvas = myCanvas;
}
move(): void {
this.myCanvas.move();
}
myCanvas: MyCanvas;
}
result:
- canvas is not drawn (ngAfterViewInit() is not called)
- button click -> in move() this.myCanvas is defined, but redraw() causes error because this.context is not defined
I also tried explicitly constructing a MyCanvas
, but that results in two objects being constructed.
I guess I’m missing something fundamental here…