BootstrapBlazor实战 Chart 图表使用(1)

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(包含链接: //github.com/densen2014 ),不得用于商业目的,基于本文修改后的作品务必以相同的许可发布。如有任何疑问,请与我联系

AlexChow

今日头条 | 博客园 | 知乎 | Gitee | GitHub