Giter VIP home page Giter VIP logo

chartjs.blazor's Introduction

Chart.js interop with Blazor

License: MIT GitHub issues GitHub forks GitHub stars

Join the chat at https://gitter.im/ChartJs-Blazor/community

NuGet Downloads

Netlify Status

Introduction

This is a Blazor library that wraps Chart.js. You can use the library in both client- and server-side projects. See the Getting Started, browse the samples or reach out on Twitter if you need help.

Don't know what Blazor is? Read here.

Getting started

Prerequisites

You need an IDE that supports Blazor and .Net Core SDK 3.x+

  1. Visual Studio 2019 (Community Edition is fine) or VisualStudio for Mac or Jetbrains Rider
  2. .NET Core 3.0 or newer

Installation

There's a NuGet package available: ChartJs.Blazor

In case you prefer the command line:

dotnet add package ChartJs.Blazor

Usage

Assets

Before you can start creating a chart, you have to add some static assets to your project. These come bundled with ChartJs.Blazor, so you only need to add a few lines to your Index.html/_Host.cshtml.

In your _Host.cshtml (server-side) or in your index.html (client-side) add the following lines to the body tag after the _framework reference

<!-- Reference the included moment.js javascript file. -->
<script src="_content/ChartJs.Blazor/moment-with-locales.min.js" type="text/javascript" language="javascript"></script>

<!-- Reference the included ChartJs javascript file. -->
<script src="_content/ChartJs.Blazor/Chart.min.js" type="text/javascript" language="javascript"></script>

<!-- This is the glue between the C# code and the ChartJs charts -->
<script src="_content/ChartJs.Blazor/ChartJsBlazorInterop.js" type="text/javascript" language="javascript"></script>

<!-- Some styling -->
<link rel="stylesheet" href="_content/ChartJs.Blazor/ChartJSBlazor.css" />

Imports

Now add a reference to ChartJs.Blazor in your _Imports.razor

@using ChartJs.Blazor;

Chart

Now you can create a .razor file where you display one of the charts. Let's show a pie chart with 4 slices πŸ•.

Make your page known to the router by adding a @page statement

@page "/MyPieChart"

Then add a few @using statements

@using ChartJs.Blazor.Charts
@using ChartJs.Blazor.ChartJS.PieChart
@using ChartJs.Blazor.ChartJS.Common.Properties
@using ChartJs.Blazor.Util

Below the @using statements add a ChartJsPieChart component

<ChartJsPieChart @ref="_pieChartJs" Config="@_config" Width="600" Height="300"/>

The last step is to make the ChartJsPieChart from above, reachable from your code to configure it and to give it some data to display. In the @code section of your .razor file create matching variables to reference the chart and its configuration. Finally, give your chart a title and some data. The finished code should look like this:

private PieConfig _config;
private ChartJsPieChart _pieChartJs;

protected override void OnInitialized()
{
    _config = new PieConfig
    {
        Options = new PieOptions
        {
            Title = new OptionsTitle
            {
                Display = true,
                Text = "Sample chart from Blazor"
            },
            Responsive = true,
            Animation = new ArcAnimation
            {
                AnimateRotate = true,
                AnimateScale = true
            }
        }
    };

    _config.Data.Labels.AddRange(new[] { "A", "B", "C", "D" });

    var pieSet = new PieDataset
    {
        BackgroundColor = new[] { ColorUtil.RandomColorString(), ColorUtil.RandomColorString(), ColorUtil.RandomColorString(), ColorUtil.RandomColorString() },
        BorderWidth = 0,
        HoverBackgroundColor = ColorUtil.RandomColorString(),
        HoverBorderColor = ColorUtil.RandomColorString(),
        HoverBorderWidth = 1,
        BorderColor = "#ffffff",
    };

    pieSet.Data.AddRange(new double[] { 4, 5, 6, 7 });
    _config.Data.Datasets.Add(pieSet);
}

Breakdown

First, in your Index.html/_Host.cshtml you've added references to static assets from ChartJs.Blazor. During build time, library assets get packaged under _content/LibraryName.

Then, you've imported ChartJs.Blazor in your _Imports.razor. The Blazor Team mentioned that this shouldn't be necessary in the future.

In your .razor file you added the ChartJsPieChart component and gave it some width and height. You specified that the component should use the variable _config as the chart's configuration object. You also told Blazor that you want a direct reference to the chart and that the reference should be saved in your _pieChartJs variable.

When your page's OnInitialized() method is executed you're setting the chart's configuration and dataset to be displayed.

Known Limitations

Library

  • Client-side Blazor projects are currently affected by a bug in JSON.NET tracked by this issue.

    There are two known workarounds:

    • Prefered Option - add a file named Linker.xml to the root of your client-side project to instruct the Mono linker to keep a certain constructor that JSON.NET invokes via reflection. Make sure to select BlazorLinkerDescription as the build action of the Linker.xml file. In case that your IDE doesn't offer that option, simply edit the .csproj file and add this to it:

          <ItemGroup>
              <BlazorLinkerDescriptor Include="Linker.xml" />
          </ItemGroup>

      The content of the Linker.xml should be similar to this (adjust to your project's entry point assembly):

          <?xml version="1.0" encoding="UTF-8" ?>
          <!--
          This file specifies which parts of the BCL or Blazor packages must not be
          stripped by the IL Linker even if they aren't referenced by user code.
          -->
          <linker>
              <assembly fullname="mscorlib">
                  <!--
                      Preserve the methods in WasmRuntime because its methods are called by
                      JavaScript client-side code to implement timers.
                      Fixes: https://github.com/aspnet/Blazor/issues/239
                      -->
                  <type fullname="System.Threading.WasmRuntime" />
              </assembly>
              <assembly fullname="System.Core">
                  <!--
                      System.Linq.Expressions* is required by Json.NET and any
                      expression.Compile caller. The assembly isn't stripped.
                      -->
                  <type fullname="System.Linq.Expressions*" />
              </assembly>
              <!-- The app's entry point assembly is listed. -->
              <assembly fullname="ChartJs.Blazor.Sample.ClientSide" />
              <!-- Take care of System.MissingMethodException: Constructor on type 'System.ComponentModel.ReferenceConverter' not found. -->
              <assembly fullname="System">
                  <type fullname="System.ComponentModel.ReferenceConverter">
                  <method signature="System.Void .ctor(System.Type)" />
                  </type>
              </assembly>
          </linker>
    • Alternative Option - include the following line in the parent component:

      private ReferenceConverter ReferenceConverter = new ReferenceConverter(typeof(PROBLEMATIC_COMPONENT));

      where PROBLEMATIC_COMPONENT is a placeholder for the chart-component you're using inside this component (e.g. ChartJsBarChart, ChartJsPieChart, ChartJsLineChart, ..).

Samples

  • When publishing the client-side Blazor sample, the generated dist folder is missing _content\ChartJs.Blazor. This seems to be a known bug in the current version of client-side Blazor. To work around this bug you need to go to the publish folder and locate the wwwroot folder. There you should find the missing _content folder. Copy the _content folder to the dist folder. The final dist folder should look like this
β”‚   index.html
β”‚
β”œβ”€β”€β”€css
β”‚   β”‚   site.css
β”‚   β”‚
β”‚   β”œβ”€β”€β”€bootstrap
β”‚   β”‚       bootstrap.min.css
β”‚   β”‚       bootstrap.min.css.map
β”‚   β”‚
β”‚   └───open-iconic
β”‚       β”‚   FONT-LICENSE
β”‚       β”‚   ... truncated for brevity
β”‚
β”œβ”€β”€β”€_content
β”‚   └───ChartJs.Blazor
β”‚           Chart.min.js
β”‚           ChartJSBlazor.css
β”‚           ChartJsBlazorInterop.js
β”‚           moment-with-locales.min.js
β”‚
└───_framework
    β”‚   blazor.boot.json
    β”‚   blazor.server.js
    β”‚   blazor.webassembly.js
    β”‚
    β”œβ”€β”€β”€wasm
    β”‚       mono.js
    β”‚       mono.wasm
    β”‚
    └───_bin
            ChartJs.Blazor.dll
            ChartJs.Blazor.pdb
            ... truncated for brevity
            System.Xml.Linq.dll

Dig deeper

For detailed instructions read the Chart.js documentation to understand how each chart works.

A word on the samples

The current samples are flawed in many ways. If you would like to help improving them, please see this issue.

The samples folder contains three projects, one for a client-side Blazor app, another one for a server-side Blazor app and a shared project. The shared project is not really necessary but that is how we chose to avoid code duplication.

Unlike the documentation, the samples should always be up to date with the current development on master. That means, that the code you see in the samples folder on master might not actually compile on the current nuget version. To browse the samples for the latest nuget version, see the samples on the releases branch.

To make it easier for you to see what ChartJs.Blazor can do, we host the client-side samples with Netlify on www.iheartblazor.com (and a few other domains 😁). However, the demo page might lag behind a bit too so if you want to be sure, compile the samples on the releases branch.

If you go to the demo page, you should see something like this: Charts

Contributors

This projects slowly develops a community which started to give back.

Special thanks to:

  • Joelius300 for keeping the project alive, developing it further and finally giving me the needed motivation to revive it.

Many thanks to:

We're very grateful for your contributions!

Contributing

We really like people helping us with the project. Nevertheless, take your time to read our contributing guidelines here.

Also keep in mind that this library is just a bridge from Blazor (C#) to Chart.js (JavaScript) so if you have a question on how to achieve something or experience unexpected behaviour, research how to do/fix it with JavaScript and only when you know how to get the correct behaviour in JavaScript open an issue here with all that information. It will greatly help us to give feedback and prevents us from wasting our limited time on issues that aren't really connected to this library. Thank you!

chartjs.blazor's People

Contributors

esso23 avatar geracikha avatar jli103828 avatar joelius300 avatar larshg avatar mariusmuntean avatar mashbrno avatar muqeet-khan avatar sepppenner avatar srowan avatar tomaszgrzmilas avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.