How to use canvas in Angular

后端 未结 2 2026
耶瑟儿~
耶瑟儿~ 2020-12-13 18:13

The common approaching to use canvas in javascript is like :

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


        
相关标签:
2条回答
  • 2020-12-13 18:23

    do you looking for something like this?

    var canvas: HTMLCanvasElement = <HTMLCanvasElement> document.getElementById('tutorial');
    var ctx: CanvasRenderingContext2D = canvas.getContext("2d");
    
    0 讨论(0)
  • 2020-12-13 18:26

    You can accomplish this by using @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 document as much as you can, as it could bite you on the long run. Also using @ViewChild has 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.

    For a full example check out this demo


    Update

    For angular 8 you need to use ViewChild like this.

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

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

    0 讨论(0)
提交回复
热议问题