为什么 ElementRef to Canvas 在这里不起作用?

Why is ElementRef to Canvas not working here?

我尝试将图像加载到 canvas。

在模板中

<canvas #myca id="mycanvas" style="width: 600px; height; 600px; border: 2px red solid;" (mousedown)="mdown ($event)"></canvas>

组件中

@ViewChild('myca', {static: false}) myca: ElementRef <HTMLCanvasElement>;

ngOnInit ()
{
    // ctx by id works!
    //var ctx = (<HTMLCanvasElement> document.getElementById('mycanvas')).getContext('2d'); 

    // ctx by ElementRef fails!
    var ctx = this.myca.nativeElement.getContext('2d'); 

    var img1 = new Image();
    img1.src = "http://any_img_you_want.jpg";

    img1.onload = function () 
    {
        ctx.drawImage (img1, 0, 0);
    }
}

如果我通过 id 获取 ctx,它就可以工作。如果我通过 ElementRef 执行它,它将失败。 这里有什么问题?

是选角的问题。下面的代码应该可以工作:

@ViewChild('myca') myca: ElementRef;

ngOnInit () {

    const ctx = (<HTMLCanvasElement>this.myca.nativeElement).getContext('2d');

    var img1 = new Image();
    img1.src = "http://any_img_you_want.jpg";

    img1.onload = function () {
        ctx.drawImage (img1, 0, 0);
    }
}

找到原因了

在较新的 Angular 版本中,ViewChild 装饰器需要第二个参数。 只有一个我会得到打字稿错误。

如果我将静态标志从 false 更改为 true,它就会起作用。

无需特殊铸造。

@ViewChild('myca', {static: true}) myca: ElementRef;

...

var ctx = this.myca.nativeElement.getContext ("2d");