为什么 ElementRef to Canvas 在这里不起作用? [英] Why is ElementRef to Canvas not working here?

查看:26
本文介绍了为什么 ElementRef to Canvas 在这里不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I try to load an image into a 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 执行它会失败.这里有什么问题?

If I get the ctx by the id it works. If I do it by the ElementRef it fails. Whats the problem here?

推荐答案

我找到原因了.

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

In newer Angular versions the ViewChild Decorator needs 2nd parameter. With only one I would get a typescript error.

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

If I change the static flag from false to true it works.

不需要特殊的铸造.

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

...

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

这篇关于为什么 ElementRef to Canvas 在这里不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆