An error occurs when angular uses canvas

Recently, the angular front-end framework was used to add graphic verification code authentication for application login. Since there was no ready-made plug-in, canvas + JS was used, which can also be used normally, but there was an error in the compilation stage:

ERROR in src/app/login/login.component.ts(84,19): error TS2339: Property 'getContext' does not exist on type 'HTMLElement'.

Although an error is reported, it can be executed normally. It’s strange. The error code is:

let c = document.getElementById("myCanvas") ;
let ctx = c.getContext("2d");

Check the source code   getContext()   This method is. Later, I wonder if it is caused by the type. Therefore, use the type assertion (which does not affect the code operation, but only works in the compilation stage) to modify the code. Enter the following:

let c = document.getElementById("myCanvas")  as HTMLCanvasElement;
let ctx = c.getContext("2d");

The compilation passed normally. As we will see later, there is another assertion method:

let c = <HTMLCanvasElement> document.getElementById("myCanvas") ;
let ctx = c.getContext("2d");

The above can be compiled because   getContext()   Yes   HTMLCanvasElement   Therefore, we need to specify the type

 

Above

 

Similar Posts: