Javascript 如何在 Angular 中使用画布

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44426939/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:30:44  来源:igfitidea点击:

How to use canvas in Angular

javascriptangulartypescripthtml5-canvas

提问by stephzcj

The common approaching to use canvas in javascript is like :

在 javascript 中使用画布的常见方法是:

var canvas = document.getElementById('tutorial');
var ctx = canvas.getContext('2d');

but in Angular2 I cannot get the HTMLCanvasElement object, the var "canvas" only get the HTMLElement in Angular2. So how to use canvas in Angular2? And furthermore, how to use the third-party javascript in Angular2 with the language TypeScript?

但是在 Angular2 中我无法获得 HTMLCanvasElement 对象,var“canvas”只能获得 Angular2 中的 HTMLElement。那么如何在 Angular2 中使用画布呢?此外,如何在 Angular2 中使用 TypeScript 语言的第三方 javascript?

回答by realappie

You can accomplish this by using @ViewChild

您可以使用 @ViewChild

In your class do the following.

在你的课堂上做以下事情。

import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core';

@Component({
   name: 'my-component',
   // notice the variable name myCanvas
   template: `<canvas #myCanvas></canvas>`
})
export class myComponent implements AfterViewInit {
  // its important myCanvas matches the variable name in the template
  @ViewChild('myCanvas')
  myCanvas: ElementRef<HTMLCanvasElement>;

  public context: CanvasRenderingContext2D;

  ngAfterViewInit(): void {
    this.context = this.myCanvas.nativeElement.getContext('2d');
  }
}

Try to stay away from using documentas much as you can, as it could bite you on the long run. Also using @ViewChildhas an advantage over querying the DOM, once the application is compiled. Angular already knows ahead of time which element it needs to do the modifications on, rather than having to find it in the DOM.

尽量避免使用document,因为从长远来看它会咬你。@ViewChild一旦应用程序被编译,使用也比查询 DOM 有优势。Angular 已经提前知道它需要对哪个元素进行修改,而不必在 DOM 中找到它。

For a full example check out this demo

有关完整示例,请查看此演示



Update

更新

For angular 8 you need to use ViewChildlike this.

对于角度 8,您需要ViewChild像这样使用。

@ViewChild('myCanvas', {static: false}) myCanvas: ElementRef;

See How should I use the new static option for @ViewChild in Angular 8?for more information

请参阅如何在 Angular 8 中为 @ViewChild 使用新的静态选项?想要查询更多的信息

回答by Darky_Chan

do you looking for something like this?

你在寻找这样的东西吗?

var canvas: HTMLCanvasElement = <HTMLCanvasElement> document.getElementById('tutorial');
var ctx: CanvasRenderingContext2D = canvas.getContext("2d");