Home > Blockchain >  Change default width and height Canvas size in Angular
Change default width and height Canvas size in Angular

Time:07-30

I'm using canvas and I think the default width, and height size 300px/150px. I want to customize the width, I use Angular.

I did try to put canvas { width:400px } in app.component.css but didn't work

app.component.ts

   const canvas = document.createElement('canvas');
   const context = canvas.getContext('2d');
   context.font = '30px Arial';
   context.fillText('Hello World', 10, 50);

CodePudding user response:

This is my one example for canvas in Angular-13

app.component.ts File

import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
        
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})

export class AppComponent implements AfterViewInit {
  context: any;

  @ViewChild('myCanvas')
  private myCanvas: ElementRef = {} as ElementRef;

  ngAfterViewInit(): void {
    this.context = this.myCanvas.nativeElement.getContext('2d');
    if(this.context) {
      this.myCanvas.nativeElement.width = 400;
      this.context.font = '30px Arial';
      this.context.fillText('Hello World', 10, 50);
    }
  }
}

app.component.html File: I have added my canvas in template file like below.

<canvas #myCanvas>

Hope this help. Thanks!

  • Related