React TypeScript:类型“null”不能分配给类型“CanvasRenderingContext2D”

zaq34kh6  于 2023-08-08  发布在  TypeScript
关注(0)|答案(6)|浏览(221)

我似乎能够创建画布,但当我来获得上下文

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
    ...

字符串
错误是

Type 'CanvasRenderingContext2D | ImageBitmapRenderingContext | WebGLRenderingContext | WebGL2RenderingContext | null' is not assignable to type 'CanvasRenderingContext2D'.
  Type 'null' is not assignable to type 'CanvasRenderingContext2D'.ts(2322)

wb1gzix0

wb1gzix01#

该错误意味着resizeCanvas.getContext('2D')可以返回null,但您将其分配给CanvasRenderingContext2D类型的变量(即这不能为空)。因此,在赋值之前,您需要确保结果不为null。另外,我猜你想确保它的类型是CanvasRenderingContext2D而不是ImageBitmapRenderingContext等。您可以:

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;

字符串

j9per5c4

j9per5c42#

只需像这样声明yout变量:第一个月

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');
  }

字符串

slhcrj9b

slhcrj9b3#

以下方法将起作用

const resizeImage = async (maxSize: number) => {
const image = originalImage;
const id = positionId;
const resizeCanvas = document.createElement('canvas');
resizeCanvas.width = maxSize;
resizeCanvas.height = maxSize;
const ctx = resizeCanvas.getContext('2D') as unknown as CanvasRenderingContext2D;

字符串

h43kikqp

h43kikqp4#

而不是声明属性并在之后赋值,只需将其设置为本地,然后导出它。当你声明outside时,你需要先将它无效,canvas不接受它。
所以改变这个:

/** Canvas 2d context */
  private context: CanvasRenderingContext2D;
  
  ngAfterViewInit() {
    this.context = (this.canvas.nativeElement as HTMLCanvasElement).getContext('2d');
 ...
 }

字符串
对此:

ngAfterViewInit() {
    setTimeout(() => {
      var canvasEl: HTMLCanvasElement = this.canvas.nativeElement;
      var cx = canvasEl.getContext('2d');
      this.method(cx); <== Pass it as Parameter
    }, 1);
  }


它不会给予canvas为null的错误。希望能有所帮助。观察结果:这是针对Angular 应用程序运行的。

utugiqy6

utugiqy65#

context是做什么的?

getContext方法生成的上下文是一个对象,用于从一个 canvas 中 * 生成图像 *。
上下文可以生成2d图像或3d图像或仅位图图像。这取决于传递给方法的设置。

getContext('2d')             -> object to generate 2d images
getContext('webgl')          -> object to generate 3d images
getContext('bitmaprenderer') -> object to generate bitmap images

字符串
参见HTMLCanvasElement:getContext()方法完整列表的参数。

null context是什么意思?

这意味着浏览器不支持该类型的渲染。
浏览器无法生成图像。

你能做些什么来处理它?

接受Contextnull

// 'CanvasRenderingContext2D | ImageBitmapRenderingContext | WebGLRenderingContext | WebGL2RenderingContext | null'
const ctx: CanvasRenderingContext2D | null = resizeCanvas.getContext('2d');

// if you use another context then change accordingly
// let say WebGLRenderingContext then
const ctx: WebGLRenderingContext | null = resizeCanvas.getContext('webgl');


当您为null生成映像检查并在出现以下情况时抛出错误

getImg() : Uint8ClampedArray {
    // The browser is not able to generateimages
    if (ctx == null) {
        throw Error("2d context not supported");
    }

    ctx.drawImage(src, 0, 0, width, height);
    return ctx.getImageData(0, 0, width, height).data;
}

为什么要抛出错误?

因为无论如何,当上下文是null * 时,您将遇到运行时错误 *,因为在ctx中没有drawImage,因为它是null
所以,当浏览器不支持该功能时,你最好“自己提出错误”并“处理它”。

zz2j4svz

zz2j4svz6#

打印错误:

它是getContext("2d")而不是"2D",大小写很重要。
当传入一个无效参数时,此方法将返回null

const canvas = document.createElement('canvas');
const upperCased = canvas.getContext('2D');
const lowerCased = canvas.getContext('2d');

console.log( 'upper-cased', upperCased ) // null
console.log( 'lower-cased', lowerCased ) // { "drawImage":...

字符串

相关问题