BootstrapBlazor實戰 Chart 圖表使用(1)

AlexChow發表於2022-04-03

BootstrapBlazor元件 Chart 圖表介紹

通過給定資料,繪畫各種圖表的元件

本文主要介紹三種圖表使用:折線圖,柱狀圖,餅圖

161407646-caa3a8d4-c13c-4a91-91f8-b6ea48e7aed0
161407637-ed3ca1cc-a243-432a-89b2-7ee041832ab4
161407656-9bd4cb1d-49bb-490d-8b94-57af641c1a72

1.新建工程

新建工程b06chart,使用 nuget.org 進行 BootstrapBlazor 元件安裝, Chart 庫,字型. 將專案新增到解決方案中

dotnet new blazorserver -o b06chart
dotnet add b06chart package BootstrapBlazor
dotnet add b06chart package BootstrapBlazor.FontAwesome
dotnet add b06chart package BootstrapBlazor.Chart
dotnet sln add b06chart/b06chart.csproj

2.樣式表和Javascript 引用

增加主題樣式表到 Pages/_Layout.cshtml 檔案中

刪除 <link rel="stylesheet" href="css/bootstrap/bootstrap.min.css" />

並在下面新增三行

<link href="_content/BootstrapBlazor.FontAwesome/css/font-awesome.min.css" rel="stylesheet" />
<link href="_content/BootstrapBlazor/css/bootstrap.blazor.bundle.min.css" rel="stylesheet" />
<link href="_content/BootstrapBlazor.Chart/css/bootstrap.blazor.chart.bundle.min.css" rel="stylesheet" />

新增 Javascript 引用到 Pages/_Layout.cshtml 檔案中

<script src="_framework/blazor.server.js"></script> 之前新增

<script src="_content/BootstrapBlazor/js/bootstrap.blazor.bundle.min.js" asp-append-version="true"></script>
<script src="_content/BootstrapBlazor.Chart/js/bootstrap.blazor.chart.bundle.min.js" asp-append-version="true"></script>

3.新增增加名稱空間引用到 _Imports.razor 檔案中

@using BootstrapBlazor.Components

4.增加 BootstrapBlazorRoot 元件到 App.razor 檔案中

<BootstrapBlazorRoot>
    <Router AppAssembly="@typeof(App).Assembly">
        ...
    </Router>
</BootstrapBlazorRoot>

5.新增BootstrapBlazor服務到 Program.cs 檔案中

builder.Services.AddSingleton<WeatherForecastService>(); 後加入

builder.Services.AddBootstrapBlazor();

6.元件引數

引數 說明 可選值 預設值
Width 元件寬度支援單位 如: 100px 75%
ChartType 圖表型別 Line/Bar/Pie/Doughnut/Bubble Line

7.事件

引數 說明 型別
OnInitAsync 元件資料初始化委託方法 Func<Task>
OnAfterInitAsync 客戶端繪製圖表完畢後回撥此委託方法 Func
OnAfterUpdateAsync 客戶端更新圖表完畢後回撥此委託方法 Func<ChartAction, Task>

8.為了快速建立隨機資料,我們建立一個工具類 UtilityChart.cs

程式碼來源於bb演示工程

using BootstrapBlazor.Components;

namespace b06chart;

/// <summary>
/// Chart 工具類
/// </summary>
internal static class UtilityChart
{
    public static IEnumerable<string> Colors { get; } = new List<string>() { "Red", "Blue", "Green", "Orange", "Yellow", "Tomato", "Pink", "Violet" };

    /// <summary>
    /// 
    /// </summary>
    /// <param name="chart"></param>
    public static Task RandomData(Chart chart) => chart.Update(ChartAction.Update);

    /// <summary>
    /// 
    /// </summary>
    /// <param name="chart"></param>
    /// <param name="dsCount"></param>
    public static void AddDataSet(Chart chart, ref int dsCount)
    {
        if (dsCount < Colors.Count())
        {
            dsCount++;
            _ = chart.Update(ChartAction.AddDataset);
        }
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="chart"></param>
    /// <param name="dsCount"></param>
    public static void RemoveDataSet(Chart chart, ref int dsCount)
    {
        if (dsCount > 1)
        {
            dsCount--;
            _ = chart.Update(ChartAction.RemoveDataset);
        }
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="chart"></param>
    /// <param name="daCount"></param>
    public static void AddData(Chart chart, ref int daCount)
    {
        var limit = chart.ChartType switch
        {
            ChartType.Line => 14,
            ChartType.Bar => 14,
            ChartType.Bubble => 14,
            _ => Colors.Count()
        };

        if (daCount < limit)
        {
            daCount++;
            _ = chart.Update(ChartAction.AddData);
        }
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="chart"></param>
    /// <param name="daCount"></param>
    public static void RemoveData(Chart chart, ref int daCount)
    {
        var limit = chart.ChartType switch
        {
            ChartType.Line => 7,
            ChartType.Bar => 7,
            ChartType.Bubble => 4,
            _ => 2
        };
        if (daCount > limit)
        {
            daCount--;
            _ = chart.Update(ChartAction.RemoveData);
        }
    }
}

9.折線圖

<p>折線圖</p>

<Chart @ref="LineChart" OnInitAsync="() => OnInit(0.4f, false)" Width="50%" />

<button class="btn btn-primary" @onclick="e => UtilityChart.RandomData(LineChart)"><i class="fa fa-line-chart"></i><span>隨機資料</span></button>

@code{
    private Random Randomer { get; } = new Random();
    private int LineDatasetCount = 2;
    private int LineDataCount = 7;

    private Chart? LineChart { get; set; }

    private Task<ChartDataSource> OnInit(float tension, bool hasNull)
    {
        var ds = new ChartDataSource();
        ds.Options.Title = "Line 折線圖";
        ds.Options.X.Title = "天數";
        ds.Options.Y.Title = "數值";
        ds.Labels = Enumerable.Range(1, LineDataCount).Select(i => i.ToString());
        for (var index = 0; index < LineDatasetCount; index++)
        {
            ds.Data.Add(new ChartDataset()
            {
                Tension = tension,
                Label = $"資料集 {index}",
                Data = Enumerable.Range(1, LineDataCount).Select((i, index) => (index == 2 && hasNull) ? null! : (object)Randomer.Next(20, 37))
            });
        }
        return Task.FromResult(ds);
    }
}

10.柱狀圖

<p>柱狀圖</p>

<Chart ChartType="ChartType.Bar" OnInitAsync="() => OnInit(false)" @ref="BarChart" Width="50%" />

<button class="btn btn-primary" @onclick="e => UtilityChart.RandomData(BarChart)"><i class="fa fa-bar-chart"></i><span>隨機資料</span></button>

@code{
    private int BarDatasetCount = 2;
    private int BarDataCount = 7; 
 
    private Chart? BarChart { get; set; }

    private Task<ChartDataSource> OnInit(bool stacked)
    {
        var ds = new ChartDataSource();
        ds.Options.Title = "Bar 柱狀圖";
        ds.Options.X.Title = "天數";
        ds.Options.Y.Title = "數值";
        ds.Options.X.Stacked = stacked;
        ds.Options.Y.Stacked = stacked;
        ds.Labels = Enumerable.Range(1, BarDataCount).Select(i => i.ToString());
        for (var index = 0; index < BarDatasetCount; index++)
        {
            ds.Data.Add(new ChartDataset()
            {
                Label = $"資料集 {index}",
                Data = Enumerable.Range(1, BarDataCount).Select(i => Randomer.Next(20, 37)).Cast<object>()
            });
        }
        return Task.FromResult(ds);
    }
}

11.餅圖

<p>餅圖</p>

<Chart ChartType="ChartType.Pie" OnInitAsync="@OnInit" @ref="PieChart" Width="50%" />

<button class="btn btn-primary" @onclick="e => UtilityChart.RandomData(PieChart)"><i class="fa fa-pie-chart"></i><span>隨機資料</span></button>

@code{
    private int PieDatasetCount = 1;
    private int PieDataCount = 5;

    private Chart? PieChart { get; set; }

    private Task<ChartDataSource> OnInit()
    {
        var ds = new ChartDataSource();
        ds.Options.Title = "Pie 餅圖";
        ds.Labels = UtilityChart.Colors.Take(PieDataCount);
        for (var index = 0; index < PieDatasetCount; index++)
        {
            ds.Data.Add(new ChartDataset()
            {
                Label = $"資料集 {index}",
                Data = Enumerable.Range(1, PieDataCount).Select(i => Randomer.Next(20, 37)).Cast<object>()
            });
        }
        return Task.FromResult(ds);
    }
}

12.未完待續 ?

通過簡單的步驟,已經可以初步體驗圖表元件,由於近日事務較多,這篇只是初略的帶大家快速入門,體驗一下BootstrapBlazor的Chart 圖表使用. 下一篇章我們將會對元件進行一些調整,例如新增移除資料集,新增移除資料,X軸Y軸資料改變後如何重新整理元件,以及跟資料庫結合查詢生成圖表.

專案原始碼

Github | Gitee

關聯專案

FreeSql QQ群:4336577(已滿)、8578575(已滿)、52508226(線上)

BA & Blazor QQ群:795206915、675147445

知識共享許可協議

本作品採用 知識共享署名-非商業性使用-相同方式共享 4.0 國際許可協議 進行許可。歡迎轉載、使用、重新發布,但務必保留文章署名AlexChow(包含連結: https://github.com/densen2014 ),不得用於商業目的,基於本文修改後的作品務必以相同的許可釋出。如有任何疑問,請與我聯絡

AlexChow

今日頭條 | 部落格園 | 知乎 | Gitee | GitHub

相關文章