Create Canvas Dynamically in Angular

Create Canvas Dynamically in Angular

Canvas element is part of HTML5 and allows for dynamic, scriptable rendering of 2D shapes and bitmap images. In this post we are going to checkout how to create canvas dynamically in Angular. Angular provides an API for DOM manipulations named as Renderer which can be imported from angular/core package.

We can use Renderer API to create canvas dynamically in Angular. Renderer API allows DOM maniplulations such as Create Canvas Dynamically, Set properties of Canvas like height widht Background Fill etc. 

Create Canvas Dynamically in Angular Using Renderer

//Html

Add Template reference to html to define the canvas entry point

<div class="container" #container>
  <!-- Canvas will be added here -->

</div>


Import Renderer and ViewChild

Import the Renderer2 and Viewchild API from angular/core pakage

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


//Ts

Now in your component define the parent Element Using the ViewChild API. Secondly use the Renderer API to create Canvas Element dynamically in Angular. Provide some basic style properties and append the Canvas element to its parent element which we defined earlier using the Template Reference and ViewChild API methods.

export class AppComponent {
  @ViewChild('container') container;

  constructor(private renderer: Renderer2) {}

  ngAfterViewInit() {
    let canvas = this.renderer.createElement('canvas');
    canvas.id = 'CursorLayer';
    canvas.width = 400;
    canvas.height = 400;


    let ctx = canvas.getContext('2d');
    ctx.fillStyle = '#dddddd';
    ctx.fillRect(0, 0, canvas.width, canvas.height);


    // Append to Parent Container
    this.container.nativeElement.appendChild(canvas);
  }
}


Hope you like this post.

Happy Coding!

🔥 34 Views
Dec 10, 2022