Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does canvas drawing work in Ionic 2?

I am currently using a html5 canvas and by using ionic 2 (tap)="markPoint($event)" on the canvas in html, I am getting the position of the tap event. Below is the function which should place the mark:

public markPoint(event) {
    var position = event.center;
    let ctx = this.canvas.getContext('2d');
    ctx.beginPath();
    ctx.arc(position.x, position.y, 20, 0, 2 * Math.PI);
    ctx.fillStyle = '#00DD00';
    ctx.fill();
}

I am setting the canvas like so, where canvas is the id set in the html:

this.canvas = document.getElementById('canvas');

I don't see an issue with this code, however I am also not sure whether or not this is the best way to make marks within an application in ionic 2. Do you know if this should work, and if not why? Also if there are any better ways it would be awesome to here about them.

like image 454
nickmcblain Avatar asked Apr 21 '26 18:04

nickmcblain


1 Answers

First of all we have to make more typescript<6> friendly. It's not enough just to get the canvas object like another HTML element using the id. In this case we should help a little, so my first change will be:

this.canvas = document.getElementById('canvas');

FOR =>

this.canvas = <HTMLCanvasElement>document.getElementById('canvas');

Then your function will look something like this:

public markPoint(event) {
    var position = event.center;
    let ctx: CanvasRenderingContext2D = this.canvas.getContext("2d");
    ctx.beginPath();
    ctx.arc(position.x, position.y, 20, 0, 2 * Math.PI);
    ctx.fillStyle = '#00DD00';
    ctx.fill();
}

Hope this help.

like image 59
Carlos Fernandez Avatar answered Apr 23 '26 08:04

Carlos Fernandez