【问题标题】:Why is ElementRef to Canvas not working here?为什么 ElementRef to Canvas 在这里不起作用?
【发布时间】:2020-01-03 18:10:25
【问题描述】:

我尝试将图像加载到画布中。

在模板中

<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 来做,它会失败。 这里有什么问题?

【问题讨论】:

  • “失败”是什么意思?究竟会发生什么?
  • 代码对我来说看起来不错,所以有点奇怪。你能做一个最小的堆栈闪电战来帮助进一步调查吗?

标签: angular viewchild


【解决方案1】:

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

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

【讨论】:

  • 根据问题显示的代码,元素类型已经在声明中指定:myca: ElementRef&lt;HTMLCanvasElement&gt;
【解决方案2】:

我找到了原因。

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

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

不需要特殊的转换。

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

...

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

【讨论】:

    猜你喜欢
    • 2013-05-16
    • 2019-02-10
    • 2017-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多