I seem to be able to create the canvas but when I come to get the context
const resizeImage = async (maxSize: number) => {
const image = originalImage;
const id = positionId;
const resizeCanvas = document.createElement('canvas');
resizeCanvas.width = maxSize;
resizeCanvas.height = maxSize;
const ctx: CanvasRenderingContext2D = resizeCanvas.getContext('2D');
// ^ Error
...
The error is
Type 'CanvasRenderingContext2D | ImageBitmapRenderingContext | WebGLRenderingContext | WebGL2RenderingContext | null' is not assignable to type 'CanvasRenderingContext2D'.
Type 'null' is not assignable to type 'CanvasRenderingContext2D'.ts(2322)
The error means that resizeCanvas.getContext('2D') can return null, but you are assigning it to a variable of type CanvasRenderingContext2D (i.e. this cannot be null). So you need to make sure the result is not null before assigning it. Also I guess you want to make sure it's of type CanvasRenderingContext2D rather than ImageBitmapRenderingContext etc. You could do:
const resizeImage = async (maxSize: number) => {
const image = originalImage;
const id = positionId;
const resizeCanvas = document.createElement('canvas');
resizeCanvas.width = maxSize;
resizeCanvas.height = maxSize;
const res = resizeCanvas.getContext('2D');
if (!res || !(res instanceof CanvasRenderingContext2D)) {
throw new Error('Failed to get 2D context');
}
const ctx: CanvasRenderingContext2D = res;
Just declare yout variable like this type: CanvasRenderingContext2D | null;
export class AppComponent implements OnInit{
@ViewChild('soccerField', { static: true }) soccerCanvas: ElementRef<HTMLCanvasElement> ;
private ctx: CanvasRenderingContext2D | null;
ngOnInit(): void {
let element = this.soccerCanvas.nativeElement ;
this.ctx = element.getContext('2d');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With