How can we create drawings within an Angular2 component using canvas?

I have created a basic component using a canvas element, and I am currently resizing it with an Input property within the corresponding TypeScript class. My goal is to draw the canvas element directly inside the class. The following code snippet shows my attempt: How can I achieve this in the simplest way possible? (Note the comment in the code - I aim to draw a blue rectangle inside the canvas from the constructor).

import {Component, View, Input} from 'angular2/core';

@Component({
    selector: 'chess-diagram',
})
@View({
    template: `<canvas class='chess-diag'
     [attr.width]='_size'
     [attr.height]='_size'></canvas>`,
})
export class ChessDiagram {
    private _size: number;

    constructor(){
        this._size = 150;
        // Here I would like to draw a blue rectangle inside the canvas.
    }

    get size(){
        return this._size;
    }

    @Input () set size(newValue: number){
        this._size = Math.floor(newValue);
    }
}

Answer №1

If you want to access your canvas element, you can make use of the ViewChild annotation. Once you have a reference to it, you can manipulate it using plain vanilla JavaScript.

import {Component, View, Input, ViewChild, ElementRef} from 'angular2/core';

@Component({
    selector: 'chess-diagram',
})
@View({
    template: `<canvas #chessCanvas class='chess-diag'
     [attr.width]='_size'
     [attr.height]='_size'></canvas>`,
})
export class ChessDiagram {
    private _size: number;

    // Retrieve the element with the #chessCanvas identifier
    @ViewChild("chessCanvas") chessCanvas: ElementRef; 

    constructor(){
        this._size = 150;
    }

    ngAfterViewInit() { // Ensure the view is initialized before manipulating the element

      let context: CanvasRenderingContext2D = this.chessCanvas.nativeElement.getContext("2d");
      // Start drawing on the canvas
      context.fillStyle = 'blue';
      context.fillRect(10, 10, 150, 150);
    }

    get size(){
        return this._size;
    }

    @Input () set size(newValue: number){
        this._size = Math.floor(newValue);
    }
}

The @ViewChild gives you an ElementRef which grants access to the native canvas element through the nativeElement property.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular - Error: Cannot find module 'fs'

I've encountered an issue while trying to incorporate Node's fs module into my Angular application. It seems that the problem lies in the fact that Angular doesn't operate within a node environment. I'm wondering if there's a way ...

Top strategies for managing fixed datasets

Imagine having a dataset containing country names and their corresponding phone prefixes, like so: var countryPhonePrefixes = [ { 'name': 'Germany', 'prefix': '+49' }, { 'nam ...

Exploring the power of nested components within Angular 2

I am encountering an issue with a module that contains several components, where Angular is unable to locate the component when using the directive syntax in the template. The error message I receive states: 'test-cell-map' is not a known elemen ...

Developing in VS Code and Angular: How to create a component without a spec file

Hello fellow developers! I am currently using the latest version of VS Code for my Angular application. One feature I have been utilizing is the ability to right-click a folder and select "New component" to quickly and easily create a new Angular componen ...

Angular template fails to reflect changes after manipulating objects

There is an object defined as: $scope.allSessions = { set: {}, pending: [] }; Subsequently, a method is used to populate the set property with multiple objects like this: "2014-06-07-11-30": { blah blah } This results in a list of dates bei ...

Repeating data multiple times in ng-repeat directive

Website Development <div ng-app="templeApp" ng-controller="templeList"> <div ng-repeat="temple in temples track by $index" > <h2>{{temple.strTempleName}}</h2> <h4>{{tem ...

Exploring methods to access specific values from an array containing multiple values using Lodash in Angular 4

Hey, I have an array that looks like this: [ 0: "Migration, MD" 1: "Lution, MD" 2: "Mover, MD" 3: "Dee" 4: "Prov10A" ] I would like to extract the values that contain the word "MD" in them. In other words, I want a result like this: [ 0: "Migratio ...

Resolving CORS Issue with Passport in Node.js

I have exhausted all efforts to integrate passport into my application without success. Every login attempt with various providers (Facebook, Google, Twitter, Microsoft) has resulted in an error message similar to this: XMLHttpRequest cannot load https:// ...

There are no settings available for Google API, including access tokens, refresh tokens, API keys, or refresh handler callbacks

Attempting to establish a connection to Google search console API utilizing OAuth2 const {google} = require('googleapis'); const auth = new google.auth.OAuth2( YOUR_CLIENT_ID, YOUR_CLIENT_SECRET, YOUR_REDIRECT_URL ); const searchconsole = ...

Comparing RxJS and Async/Await: Which one is the better choice?

As an Angular/Ionic developer, I recently encountered challenges with the Async/Await pattern, prompting me to reconsider my approach. A colleague suggested using the RxJS library to handle asynchronous calls more effectively, so I delved into exploring al ...

What prevents `console.log` from working within a button click event?

Why is this not functioning correctly? <button (click)="console.log('ok');">Display Details</button> The error message reads: Cannot read property 'log' of undefined However, a console.log statement in the class construc ...

Embracing the "export ... from" feature in the TypeScript compiler

Can the tsc compiler handle this particular export statement? export {PromiseWrapper, Promise, PromiseCompleter} from 'angular2/src/facade/promise'; Your assistance is greatly appreciated! ...

Tips on incorporating a dynamic variable value as a class name within a span tag

I am a beginner in the world of JavaScript. Below is the code snippet I am working with: result.push(`<span class="mark">${str.substring(h.startOffset, h.endOffset)}</span>`); Currently, I have a variable called var className = "dynamicvalue" ...

Display a dropdown list using ng-repeat to prevent selecting the same value multiple times

Within my ng-repeat loop, I have a drop-down menu and an add button that allows users to add new drop-down menus to the list. However, I am looking for a way to restrict the second drop-down menu from selecting the same value as the first one. In other wor ...

Navigating to a specific element with a smooth scroll in Angular after changing states

While working in Angular, I'm utilizing a node package to enable smooth scrolling on my website. One challenge I'm facing is implementing a feature where clicking on a link in the navbar while on a specific history state will take the user to tha ...

Having trouble with installing a React app using npx create-react-app my-app?

description needed for image Having trouble creating a react application using npx create-react-app my-app... Encountering errors shown in the image. Attempted npm init but it was unsuccessful. Included node.js and vs code in the path. ...

What is the best way to pass a variable from a class and function to another component in an Angular application?

One of the components in my project is called flow.component.ts and here is a snippet of the code: var rsi_result: number[]; @Component({ selector: 'flow-home', templateUrl: './flow.component.html', styleUrls: ['./flow.comp ...

Is there a way for me to retrieve a variable from the response of a service that was defined within the same class in Angular 4?

import {Component, OnInit} from '@angular/core'; import {LoginService} from "../../services/login.service"; import {LoginUser} from "../../services/model"; @Component({ selector: 'login-component', templateUrl: './login.component. ...

Transform an asynchronous callback into an asynchronous generator format

I have the following function from a third-party package that I am unable to modify async function runTransaction(callback) { const client = await createClient(); try { await client.query("BEGIN"); await callback(client); } ...

Is there a way to retrieve the dates from last month using jQuery?

Currently, I am unable to select past dates with the provided code. How can I adjust it to allow for selecting dates from previous months? let firstDay = new Date(); $('#date_filter_startmonthly').datepicker({ startDate: firstDay, endDate: ...