html - 错误类型错误 : Cannot read property 'nativeElement' of undefined

标签 html angular typescript html5-canvas

我是 Angular 2 的新手,我正在研究图像裁剪插件,我想在 Canvas 上显示图像。 这是我的 html 代码

<div class="row">
  <div class="col-sm-6">
     <canvas id="layout" width="400" height="300">
        This text is displayed if your browser does not support HTML5 Canvas.
     </canvas>

这是我的 typescript 文件

import { Component, OnInit, ViewChild } from '@angular/core';
@Component({
selector: 'app-four',
templateUrl: './four.component.html',
styleUrls: ['./four.component.css']
})
export class FourComponent implements OnInit {
image: HTMLImageElement;
profPic: any;
context: CanvasRenderingContext2D;

constructor() { }
@ViewChild('layout') canvas;
@ViewChild('photo') photo;

ngOnInit() {
const _canvas = this.canvas.nativeElement;
//let photo = this.photo.nativeElement;
this.context = (<HTMLCanvasElement>_canvas).getContext('2d');
  this.image = new Image();
  this.image.src = '../../assets/images/1.jpg';

this.context.drawImage(this.image,20,20,500,260);

}
}

我有错误

错误类型错误:无法读取未定义的属性“nativeElement”

请帮我解决这个问题

谢谢

最佳答案

制作layout局部模板变量

 <canvas #layout id="layout" width="400" height="300">
        This text is displayed if your browser does not support HTML5 Canvas.
     </canvas>

WORKING DEMO

关于html - 错误类型错误 : Cannot read property 'nativeElement' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48678994/

相关文章:

html - 根据 div 高度 bootstrap 自动调整面板的高度

typescript - 带有 TypeScript 的可选泛型类型

javascript - 使用此 HTML/Javascript/CSS 生成随机字符串?

php - 如何在输入字段中显示占位符名称而不是值名称

javascript - 在 Angular 中使用 Rxjs 更新来自不同 Json 源的 Json 中的数据

syntax-error - Angular 2教程-第4部分: “SyntaxError: Unexpected token <(…)”

typescript - Typescript 中的模板文字推理和缩小范围

javascript - typescript :_this2.onClick 不是函数

html - 如何启用 HTML TextArea 自动调整宽度?

html - 中间有点的水平线