Canvas in ionic 4

Hello,

I used ionic 3 with a canvas to make a plan and I switched to ionic 4, only I can not use canvas with ionic 4, but I use the same code.

Below, I just put the code that allowed to create the canvas. (This code works for ionic 3 but not for ionic 4).
In the .ts :
import { Component, ElementRef, ViewChild } from ‘@angular/core’;

@Component({
selector: ‘app-tab2’,
templateUrl: ‘tab2.page.html’,
styleUrls: [‘tab2.page.scss’]
})
export class Tab2Page {

@ViewChild(‘canvas’) canvasEl : ElementRef;
private _CANVAS : any;
private _CONTEXT : any;

constructor(){}

ionViewDidLoad() : void
{
   this._CANVAS 		    = this.canvasEl.nativeElement;
   this._CANVAS.width  	= 500;
   this._CANVAS.height 	= 500;

   this.setupCanvas();
}


setupCanvas() : void
{
  this._CONTEXT = this._CANVAS.getContext('2d');
  this._CONTEXT.clearRect(0, 0, this._CANVAS.width, this._CANVAS.height);
  this._CONTEXT.fillStyle = "#ff0000";
  this._CONTEXT.fillRect(100, 100, 400, 400);
}

}

In the .html :
<ion-content>
<div class=“ion-canvas”>
<canvas #canvas></canvas>
</div>
</ion-content>

Thank you in advance for your help

Have you tried changing ionViewDidLoad to ionViewDidEnter?
I think that is all you need.

Hi @Antoine44 below code is working. check that.

ngAfterViewInit() {
this.canvasElement = this.canvas.nativeElement;
this.scaleCanvas(this.canvasElement);
window.addEventListener(‘resize’, () => { this.scaleCanvas(this.canvasElement); });
}

scaleCanvas(canvasElement) {
this.renderer.setElementAttribute(canvasElement, ‘width’, this.platform.width() + ‘’);
this.renderer.setElementAttribute(canvasElement, ‘height’, this.platform.height() + ‘’);
}

changeColour(colour) {
this.currentColour = colour;
}

changeSize(size) {
this.brushSize = size;
}

handleStart(ev) {
this.lastX = ev.touches[0].pageX;
this.lastY = ev.touches[0].pageY;
}

handleMove(ev) {
const ctx = this.canvasElement.getContext(‘2d’);
const currentX = ev.touches[0].pageX;
const currentY = ev.touches[0].pageY;

ctx.beginPath();
ctx.lineJoin = 'round';
ctx.moveTo(this.lastX, this.lastY);
ctx.lineTo(currentX, currentY);
ctx.closePath();
ctx.strokeStyle = this.currentColour;
ctx.lineWidth = this.brushSize;
ctx.stroke();

this.lastX = currentX;
this.lastY = currentY;

}

clearCanvas() {
const ctx = this.canvasElement.getContext(‘2d’);
ctx.clearRect(0, 0, this.canvasElement.width, this.canvasElement.height);
}