MAUI Blazor学习3-绘制ECharts图表

MAUI Blazor学习3-绘制ECharts图表

 MAUI Blazor系列目录 

  1. MAUI Blazor学习1-移动客户端Shell布局 - SunnyTrudeau - 博客园 (cnblogs.com)
  2. MAUI Blazor学习2-创建移动客户端Razor页面 - SunnyTrudeau - 博客园 (cnblogs.com)

 既然选择了MAUI Blazor,投身Html,那肯定要把Html生态圈的能力用起来。怎么能少得了ECharts这么炫酷的好东西?  

引入ECharts

 MAUI Blazor项目不是Web网站项目,不能像Blazor Server项目那样通过添加客户端库菜单直接引入ECharts,但是可以找一个Blazor Server项目,把它的echarts.min.js库文件复制过来使用即可。复制后的文件位置在: 

D:\Software\gitee\mauiblazorapp\MaBlaApp\wwwroot\lib\echarts 

编写Razor页面代码

 我们就用MAUI Blazor项目模板自带的天气预报的数据,提取它的日期和温度,画一条简单的折线图。注意等待OnAfterRenderAsync渲染页面完成之后,再调用JavaScript互操作的功能。

@page "/counter"
@using MaBlaApp.Data
@inject IJSRuntime JSRuntime
@inject WeatherForecastService ForecastService

<h3>天气温度图表</h3>

<!-- 为 ECharts 准备一个具备大小(宽高)的 DOM -->
<div id=@weatherChartId style="width:100%;height:400px;"></div>

@code {

    public readonly string weatherChartId = "weatherChartId";

    private WeatherForecast[] forecasts;

    protected override async Task OnInitializedAsync()
    {
        forecasts = await ForecastService.GetForecastAsync(DateTime.Now);
    }

    //获取天气温度数据
    private object GetDailyWeather()
    {
        var days = forecasts.Select(x => $"{x.Date:M}").ToArray();
        var temperatures = forecasts.Select(x => x.TemperatureC).ToArray();
        var dailyWeather = new
        {
            Days = days,
            Temperatures = temperatures,
        };

        return dailyWeather;
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (!firstRender)
            return;

        //等到网页渲染完成之后,再初始化ECharts绘图
        try
        {
            //获取天气温度数据
            var dailyWeather = GetDailyWeather();

            //绘制天气温度图表
            await JSRuntime.InvokeVoidAsync("weatherWin.DrawCharts", weatherChartId, dailyWeather);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"天气温度绘图错误, {ex}");
        }
    }
}

 

编写JavaScript绘图函数

新建JavaScript代码文件,定义一个weatherWin对象,它提供DrawCharts函数绘制日期气温图表。

D:\Software\gitee\mauiblazorapp\MaBlaApp\wwwroot\js\weather.js 

//天气图表
window.weatherWin = {

    //绘制天气温度图表
    DrawCharts: function (chartId, dailyWeather) {

        this.InitCharts(chartId);

        this.FillCharts(dailyWeather);
    },

    //初始化图表
    InitCharts: function (chartId) {

        var weatherChartElement = document.getElementById(chartId);
        if (weatherChartElement == null)
            return;

        // 基于准备好的dom,初始化echarts实例
        var weatherChart = echarts.init(weatherChartElement);

        weatherChart.showLoading();

        window.weatherWin.weatherChart = weatherChart;
    },

    //填充图表的数据
    FillCharts: function (dailyWeather) {

        if (this.weatherChart == null)
            return;

        const days = dailyWeather.days;
        const temperatures = dailyWeather.temperatures;

        var weatherLineOption = {

            xAxis: {
                type: 'category',
                name: '日期',
                data: days,
            },
            yAxis: {
                type: 'value',
                name: '温度',
                min: -20,
                max: 60,
            },

            series: [
                {
                    type: 'line',
                    label: {
                        show: true,
                        position: 'bottom',
                    },
                    data: temperatures,
                },
            ]
        };

        // 使用刚指定的配置项和数据显示图表。
        this.weatherChart.setOption(weatherLineOption);

        this.weatherChart.hideLoading();
    },

};

 

 ECharts的折线图教程可以参考官网 

https://echarts.apache.org/handbook/zh/how-to/chart-types/line/basic-line  

引入JavaScript文件

 这里需要注意,MAUI Blazor引入JavaScript文件的路径,跟Blazor Server是不一样的。如果按照Blazor Server项目的写法: 

    <script src="~/lib/echarts/echarts.min.js"></script> 

    <script src="~/js/weather.js"></script>

 

运行后会报错,其实不是找不到对象,而是根本没有加载js文件。 

[DOTNET] 天气温度绘图错误, Microsoft.JSInterop.JSException: Could not find 'weatherWin.DrawCharts' ('weatherWin' was undefined).

  

正确的写法,不需要前面的~/ 

D:\Software\gitee\mauiblazorapp\MaBlaApp\wwwroot\index.html 

    <script src="_framework/blazor.webview.js" autostart="false"></script> 

    <script src="lib/echarts/echarts.min.js"></script> 

    <script src="js/weather.js"></script> 

 

测试效果

 在手机模拟器上跑一下,效果出来了。

DEMO代码地址:https://gitee.com/woodsun/mauiblazorapp

 

posted on 2023-01-03 19:12  SunnyTrudeau  阅读(1636)  评论(0编辑  收藏  举报