2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

BlazorでJavaScript(今回はECharts)を使う

Last updated at Posted at 2024-03-02

動作画面

image.png

前提

.Net8 Blaozr WebAssemblyからJavaScriptのEChartsを使います。

設定

  • EChartsをここからダウンロードしwwwrootにechartsフォルダを作成し保存する

利用

EChartsを表示するタグを作成する

<div @ref="chartDiv" id="chartDiv" style="width: 600px; height: 400px;"></div>

@ref="chartDiv"でDivタグを参照できるようにしておきます

EChartsを読み込み初期化する

private ElementReference chartDiv; //divタグ
private IJSObjectReference? _jsECharts; //EChartsのインスタンス

protected override async Task OnAfterRenderAsync(bool firstRender)
{
    if (firstRender)
    {
        //echarts.jsを読み込む
        await JSRuntime.InvokeAsync<IJSObjectReference>("import", "./echarts/echarts.js");

        //echartsの初期化 インスタンスを_jsEChartsで受ける
        _jsECharts = await JSRuntime.InvokeAsync<IJSObjectReference>("echarts.init", chartDiv);

    }
}

EChartsを表示する

//表示データ
var options = new
{
    animationDuration = 0,
    tooltip = new { },
    xAxis = new
    {
        data = new string[] { "shirt", "cardigan", "chiffon", "pants", "heels", "socks" }
    },
    yAxis = new { },
    series = new[]
    {
        new
        {
            name = "sales",
            type = "line",
            data = new int[] { 5, 20, 36, 10, 10, 20 }
        }
    }
};

//表示データを設定
await _jsECharts.InvokeVoidAsync("setOption", options);

EChartsをダウンロードではなくCDNから利用する場合は

//echarts.jsを読み込む
- await JSRuntime.InvokeAsync<IJSObjectReference>("import", "./echarts/echarts.js");
+ await JSRuntime.InvokeAsync<IJSObjectReference>("import", "https://cdn.jsdelivr.net/npm/echarts@5.5.0/dist/echarts.min.js");

とやってください

動作サンプルはGithubに置いておきます。

2
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?