Click here to Skip to main content
14,494,314 members

Draw Dynamic ASP.NET Core Blazor Bubble Chart using Canvas Extensions

Rate this:
0.00 (No votes)
Please Sign up or sign in to vote.
0.00 (No votes)
5 Mar 2020CPOL
How to draw our own Bubble chart using ASP.NET Core Blazor Web Application using HTML5 Canvas
In this article, we will see in detail how to draw our own bar chart for ASP.NET Core Blazor Web Application using HTML5 Canvas Blazor Extensions. We have planned to write a series of articles. In each article, we will explain how to draw our own chart for ASP.NET Core Blazor Web Application using HTML5 Canvas Blazor Extensions.

Introduction

Image 1

In this series, we will see one by one in detail starting from:

  1. Dynamic Bar Chart using Blazor Canvas Extensions
  2. Dynamic Bubble Chart using Blazor Canvas Extensions (Current)
  3. Dynamic Line Chart using Blazor Canvas Extensions
  4. Dynamic Bar & Line Chart using Blazor Canvas Extensions

In today's article, we will see how to draw our own bubble chart using ASP.NET Core Blazor Web Application using HTML5 Canvas.

Background

Using the Code

Step 1: Create ASP.NET Core Blazor Server Application

After installing all the prerequisites listed above, click Start >> Programs >> Visual Studio 2019 >> Visual Studio 2019 on your desktop. Click New >> Project.

Image 2

Select Blazor App and click Next button.

Image 3

Select your project folder and enter your Project name and then click Create button.

Image 4

Select Blazor Server App.

Image 5

After creating ASP.NET Core Blazor Server Application, wait for a few seconds. You will see the below structure in solution explorer.

Image 6

In the Data folder, we can add all our Models, DBContext Class, Services and Controller, we will see that in this article.

In the Pages folder, we can add all our component files.component file, all should have the .razor extension with the file name.

In the Shared folder, we can add all left menu form NavMenu.razor files and change the main content from the MainLayout.razor file.

In the _Imports.razor file, we can see all set of imports have been added in order to use in all component pages.

In the App.razor file, we will add our main component to be displayed by default when run in browser.Appsertings.json can be used to add the connection string.

Startup.cs file is an important file where we add all our endpoints example like Controller end points, HTTP Client, add services and dbcontext to be used in startup Configuration method.

Run to Test the Application

When we run the application, we can see that the left side has navigation and the right side contains the data. We can see as the default sample pages and menus will be displayed in our Blazor web site. We can use the pages or remove it and start with our own page.

Image 7

Step 2: Install the Packages

To use the Blazor Canvas Extension in our Blazor Application, we need to install the below packages:

  • Blazor.Extensions.Canvas

Right click the solution and click on the Manage Nuget package. Search for all the packages and install all the needed packages like the below image:

Image 8

After installing the package, we can confirm it from Dependencies Packages.

Image 9

Note: Add the blazor.extensions.canvas.js file.

Open the _Host.cshtml file and add the below code inside the head tag.

<script src="_content/Blazor.Extensions.Canvas/blazor.extensions.canvas.js"></script>

Image 10

Step 3: Create Model Class

Next, we need to create the Model class for using in our application for binding the Item name and Item count in the Bar Chart.

Right click the Data folder and create new class file as “ItemMaster.cs”.

Image 11

In the class, we add the property field name that is the same as the code below:

public String ItemName { get; set; }

public int SaleCount { get; set; }

Creating Service Class

Next, we create the ItemMasterService class in order to bind the result in chart with sample Item details with the Item Name and Sale Count per each item. For this, we right click on the Data folder and click on Add New Item to add our ItemMasterService class.

Image 12

In this class, we create a method to get the ItemMaster details with sample 5 records of Items with item Name and Sale count per item as random values.

public class ItemMasterService
    {
        public Task<ItemMaster[]> GetItemMasters()
        {
            var rng = new Random();
            int ivale = 0;
            return Task.FromResult(Enumerable.Range(1, 5).Select(index => new ItemMaster
            {
                ItemName = "itm" + rng.Next(1, 100),
                SaleCount = rng.Next(20, 100),
            }).ToArray()); 
        }
    }

Step 4: Add the Service to the Startup.cs

We need to add the services created by us to the Startup.cs ConfigureServices method.

services.AddSingleton<ItemMasterService>();

Step 5: Working with Client Project

First, we need to add the Razor Component page.

Add Razor Component

To add the Razor Component page, right click the Pages folder from the Client project. Click on Add >> New Item >> Select Razor Component >> Enter your component name. Here, we have given the name as DrawingSample.razor.

Note all the component files need to have the extensions as .razor.

Image 13

In Razor Component Page, we have three parts of code as first is the Import part where we import all the references and models for using in the component, HTML design and data bind part and finally, we have the function part to call all the web APIs to bind in our HTML page and also to perform client-side business logic to be displayed in Component page.

Import Part

First, we import all the needed support files and references in our Razor View page. Here, we have first imported our Model class to be used in our view and also imported Blazor Canvas Extension for drawing our own chart control for Blazor applications.

@page "/drawingsample"

@using Blazor.Extensions.Canvas
@using Blazor.Extensions;
@using Blazor.Extensions.Canvas.Canvas2D;
@using ClazorCharts.Data
@inject ItemMasterService MasterService

HTML Design and Data Bind Part

Next, we design our DrawingSample details page to display the Bar Chart with item name and Sales count per item. Here, we have added the Blazor Extension HTML5 canvas in our Blazor HTML design part for drawing the bar chart.

<h3>Shanu - Draw Bar Chart using Blazor Canvas Extensions</h3>
<hr />  
<BECanvas Width="500" Height="500" @ref="_canvasReference"></BECanvas> 

Function Part

Function part to get the Service result and bind the result in array and to draw and plot the values for displaying the bar chart.
Here, first we declare the ItemsArray to get bind the result of Item Mater in BarChart.
Next, we create a string array as pirChartColor to draw each bar with different color from the array.
In OnInitializedAsync, we get the ItemMasterService result and bind the result in the ItemsArrys.
In OnAfterRenderAsync method, we draw the Bar Chart using C# draw objects to the Canvas. We get all item names and value using foreach of Item Array and here we plot all values and draw Bubble chart using the Array values. Using the value, we will draw our Bubble chart on canvas tag from this method.

Bubble Chart

Bubble chart usually has minimum 3 variables as one is the Bubble Size and X plot value and y plot value. Here in our example, the Bubble size is or SaleCount values and xvalue and y values to draw the bubble inside our chart.

@code {

    private Canvas2DContext _context;

    protected BECanvasComponent _canvasReference;

    ItemMaster[] itemsArrys;

    private static readonly string[] pirChartColor = new[]
      {
      "#3090C7", "#BDEDFF", "#F9B7FF", "#736AFF", "#78C7C7", 
      "#B048B5", "#4E387E","#7FFFD4", "#3EA99F", "#EBF4FA", "#F9B7FF", "#8BB381",
          //"#6CBB3C", "#F87217", "#EAC117", "#EDDA74", "#CD7F32", 
          //"#CCFB5D", "#FDD017", "#9DC209", "#E67451", "#728C00","#617C58", "#64E986"
        };

    protected override async Task OnInitializedAsync()
    {
        itemsArrys = await MasterService.GetItemMasters();
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        lastend = 0;
        xSpace = 10;
        XvalPosition = xSpace;
        maxDataVal = itemsArrys.Max(row => row.SaleCount);
        noOfPlots = itemsArrys.Length;
        chartWidth = Convert.ToInt32(_canvasReference.Width);

        chartHeight = Convert.ToInt32(_canvasReference.Height);

        int widthcalculation = 
            (Convert.ToInt32(_canvasReference.Width) - 100) / itemsArrys.Length;

        chartHeight = Convert.ToInt32(_canvasReference.Height) - 40;

        this._context = await this._canvasReference.CreateCanvas2DAsync();
        int colorval = 0;

        // Draw the axises

        await this._context.BeginPathAsync();
        await this._context.MoveToAsync(xSpace, xSpace);

        // first Draw Y Axis

        await this._context.LineToAsync(xSpace, chartHeight);

        // Next draw the X-Axis

        await this._context.LineToAsync
              (Convert.ToInt32(_canvasReference.Width) - 10, chartHeight);
        await this._context.StrokeAsync();
       
      int  varbubbleSize = 30;  
  
   int ival = 1; 

        @foreach (var itemsArry in itemsArrys)
        {
            // Draw Xaxis Plots Line and Text   ***********

            XvalPosition = XvalPosition + widthcalculation;
            await this._context.MoveToAsync(XvalPosition, chartHeight);
            await this._context.LineToAsync(XvalPosition, chartHeight + 15);
            await this._context.StrokeAsync();
            await this._context.SetFillStyleAsync("#034560");
            await this._context.SetStrokeStyleAsync("#034560");
            await this._context.SetFontAsync("12pt Calibri");
            await this._context.StrokeTextAsync
                  (itemsArry.ItemName, XvalPosition - 40, chartHeight + 24);

            //  EndXval Plotting  ************
            ////Draw Bar Graph  **************==================********************

            await this._context.SetFillStyleAsync(pirChartColor[colorval]);

            await this._context.SetStrokeStyleAsync(pirChartColor[colorval]);

            await this._context.BeginPathAsync();

            varbubbleSize = itemsArry.SaleCount;
            if(itemsArry.SaleCount>70)
            {
                varbubbleSize = itemsArry.SaleCount-10;
            }

            await this._context.ArcAsync(getXPlotvalue(ival)-6, 
            getYPlotVale(varbubbleSize-10), varbubbleSize, varbubbleSize, Math.PI * 2, true);
            await this._context.FillAsync();
            await this._context.StrokeAsync();
            await this._context.SetFillStyleAsync("#034560");
            await this._context.SetStrokeStyleAsync("#034560");
            await this._context.SetFontAsync("12pt Calibri");
            await this._context.StrokeTextAsync(itemsArry.SaleCount.ToString(), 
            getXPlotvalue(ival)-12, getYPlotVale(itemsArry.SaleCount)+46);
            await this._context.SetStrokeStyleAsync("#C0C0C0");             

            colorval = colorval + 1;

            ival = ival + 1;
        }
    }

Method to get X plot and Y Plot Value: Here, we calculate to draw our Chart item in X and in Y Axis.

// to return the x-Value  
private double getXPlotvalue(int val) {  

return Convert.ToDouble((chartWidth-40) / noOfPlots) * val + (xSpace * 1.5) - 20; 
}  
  
// Return the y value  
private double  getYPlotVale(int val) {  
   return chartHeight - (((chartHeight - xSpace) / maxDataVal) * val);  
  
}  }

Navigation Menu

Now we need to add this newly added DrawingSample Razor page to our left Navigation. For adding this, open the Shared Folder and open the NavMenu.cshtml page and add the menu.

<li class="nav-item px-3">
            <NavLink class="nav-link" href="DrawingSample">
                <span class="oi oi-list-rich" aria-hidden="true"></span> Bar Chart
            </NavLink>
        </li>

Build and Run the Application

Image 14

Points of Interest

In this sample, we have used the simple method to display the Bubble Chart within 0 to 100 range values. In order to use for many scales, we can extend this chart to draw the Legend and other details. As this is our own Chart, we can add any functions as per our requirement. In the next article, we will see in detail about how to make our own other chart using ASP.NET Blazor.

History

  • 6th March, 2020: BlazorChartSrc.zip

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

syed shanu
Team Leader
India India
Microsoft MVP | Code Project MVP | CSharp Corner MVP | Author | Blogger and always happy to Share what he knows to others. MyBlog

My Interview on Microsoft TechNet Wiki Ninja Link

Comments and Discussions

 
-- There are no messages in this forum --
Article
Posted 5 Mar 2020

Stats

6.3K views
45 downloads
5 bookmarked