I tried to add to Blazor Server app graphs by using ChartJS. I used tutorial after some tweaks it started to work but no luck with plugin zoom.
I have used .Net 7.0, ChartJS 4.4.0 and zoom plugin 2.0.1.
I included js files in my project and added them to _Host.cshtml file:
<script src="~/js/hammerjs.js"> </script>
<script src="~/lib/Chart.js/dist/chart.umd.min.js" type="module"></script>
<script src="~/lib/Chart.js/chart-plugin-zoom.js" type="module"></script>
<script src="~/js/chartInit.js"> </script>
so far i end up with config like that:
I have component for Chart:
@inject IJSRuntime JSRuntime
<div style="width:1000px; height:1000px;">
<canvas id="@Id"></canvas>
</div>
@code {
public enum ChartType
{
Pie,
Bar,
Line
}
[Parameter]
public string Id { get; set; }
[Parameter]
public ChartType Type { get; set; }
[Parameter]
public string[] Labels { get; set; }
[Parameter]
public object[] Dataset { get; set; }
protected override async Task OnAfterRenderAsync(bool firstRender)
{
var config = new
{
type = Type.ToString().ToLower(),
options = new
{
responsive = true,
spanGaps = true,
},
scales = new
{
x = new
{
type = "time"
},
y = new
{
beginAtZero = true
}
},
data = new
{
Datasets = Dataset,
Labels = Labels
},
plugins = new
{
zoom = new
{
pan = new
{
enabled = true,
mode = "x"
},
zoom = new
{
wheel = new
{
enabled = true
},
mode = "x",
drag = new
{
enabled = true
}
}
}
}
};
await JSRuntime.InvokeVoidAsync("console.log", config);
await JSRuntime.InvokeVoidAsync("setup", Id, config);
}
}
Using this component:
<Chart Id="pie1" Type="@Chart.ChartType.Line"
Dataset="@(new[] {
new JsChart_LineDataSet("1","blue",new List<float>(){4.0f, 6.0f, 9.0f, 12.0f,5f,9f}),
new JsChart_LineDataSet("2","green",new List<float>(){14.0f, 8.0f, 4.0f, 15.0f,11f,9f}),
new JsChart_LineDataSet("3","red",new List<float>(){12.0f, 3.0f, 7.0f, 35.0f,26f,22f}),
new JsChart_LineDataSet("4","orange",new List<float>(){1.0f, 12.0f, 3.0f, 6.0f,12f,24f})
}
)"
Labels="@(new[] { "0.1" , "0.2", "0.3", "0.4","0.5","0.6" })">
</Chart>
and the helper class:
public class JsChart_LineDataSet
{
public string label { get; set; }
public string backgroundColor { get; set; }
public string borderColor { get; set; }
public List<float> data { get; set; }
public JsChart_LineDataSet(string label, string backgroundColor, List<float> data)
{
this.label = label;
this.backgroundColor = backgroundColor;
this.data = data;
this.borderColor = backgroundColor;
}
}
result in browser:
I get no errors or warnings and panning or zooming don't work.
Have someone similar problem and have solution?