У меня есть линейная диаграмма Chart JS с двумя осями Y.Я столкнулся с проблемой, когда диаграмма загружается, она никогда не прекращает расти по высоте, как если бы она была в цикле, когда я в последний раз запускал ее, ее высота превышала 150000 пикселей, прежде чем я ее остановил.Это никогда не перестает расти!
Я использую C # для заполнения наборов данных и меток и создаю JS из этого для диаграммы.Я использую аналогичный код для одной диаграммы серии, и он отлично работает.
Я проверил, что это не проблема асинхронности, и я потратил целый день, пытаясь ее решить.
Я положилстроку в ViewBag
и отправьте ее в Razor View
с именем @Html.Raw(ViewBag.HtmlStr)
.
Код C # достаточно прост.
string tempValues = "";
string humValues = "";
chart = "<canvas id=\"myChart\" width=\"400\" height=\"400\"></canvas>";
chart += "<script>";
chart += " var ctx = document.getElementById(\"myChart\").getContext('2d');";
chart += " var detailsChart = new Chart(ctx, {";
chart += " type: 'line',";
chart += " data: {";
chart += "labels: [";
//X Axes
for (int i = 0; i < dt.Rows.Count; i++)
{
chart += "'" + Convert.ToDateTime(dt.Rows[i]["CombineDateTime"]).ToString("dd.MMM.yyyy HH:mm") + "',";
}
chart = chart.Substring(0, chart.Length - 1);
chart += "],";
chart += " datasets: [{";
chart += " fill: false,";
chart += " pointRadius: 0,";
chart += " borderWidth: 3,";
chart += " bordercolor: '#800080',";
chart += " backgroundColor: '#800080',";
chart += " borderColor: '#800080',";
chart += " label: 'Temperature °C',";
chart += " yAxisID: 'Temperature',";
chart += " data: [";
//Y Axes
for (int i = 0; i < dt.Rows.Count; i++)
{
tempValues += dt.Rows[i]["Temperature"].ToString() + ",";
}
tempValues = tempValues.Substring(0, tempValues.Length - 1);
chart += tempValues;
chart += " ]},";
chart += " {";
chart += " fill: false,";
chart += " pointRadius: 0,";
chart += " borderWidth: 3,";
chart += " bordercolor: '#00B2EE',";
chart += " backgroundColor: '#00B2EE',";
chart += " borderColor: '#00B2EE',";
chart += " label: 'Humidity %RH',";
chart += " yAxisID: 'Humidity',";
chart += "data: [";
//Y Axes
for (int i = 0; i < dt.Rows.Count; i++)
{
humValues += dt.Rows[i]["Humidity"].ToString() + ",";
}
humValues = humValues.Substring(0, humValues.Length - 1);
chart += humValues;
chart += " ]";
chart += "}],";
chart += " },";
chart += " options:";
chart += " {";
chart += " responsive: true,";
chart += " legend: { position: 'top'},";
chart += " maintainAspectRatio: false,";
chart += " tooltips: { mode: 'index', intersect: false,}, hover: { mode: 'nearest', intersect: true},";
chart += " scales:";
chart += " {";
chart += " yAxes: [{";
chart += " id: 'Temperature',";
chart += " type: 'linear',";
chart += " position: 'left',";
chart += " ticks:";
chart += " {";
chart += " max: 135,";
chart += " min: 0,";
chart += " steps: 10,";
chart += " stepValue: 5,";
chart += " callback: function(value, index, values) {";
chart += " return value.toFixed(2) + '°C';";
chart += " },";
chart += " },";
chart += " }, {";
chart += " id: 'Humidity',";
chart += " type: 'linear',";
chart += " position: 'right',";
chart += " ticks:";
chart += " {";
chart += " max: 30,";
chart += " min: 0,";
chart += " steps: 10,";
chart += " stepValue: 5,";
chart += " callback: function(value, index, values) {";
chart += " return value.toFixed(2) + ' %RH';";
chart += " },";
chart += " },";
chart += " }],";
chart += " xAxes: [{";
chart += " display: true,";
chart += " ticks: { autoSkip: true, maxTicksLimit: 50 },";
chart += " beginAtZero: true,";
chart += " labelString: 'Date/Time'";
chart += " }],";
chart += " }";
chart += " }";
chart += " });";
chart += "</script>";
У меня есть следующее в Razor View
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="~/lib/Chart.js/Chart.js"></script>
<script src="~/lib/moment.js/moment.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-annotation/0.5.7/chartjs-plugin-annotation.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>
<script src="https://cdn.jsdelivr.net/npm/hammerjs@2.0.8"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-zoom@0.7.0"></script>
<div class="card" style="margin-top:25px;width:100%">
<div class="card-header" style="background-color:#03A9F4;color:white;">
<h5>Review Data</h5>
</div>
<div class="card-body">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<a href="@Url.Action("Index", "ProjectPrep")"><img src="~/images/icons8-go-back-48.png" alt="Back" /></a>
</div>
<div class="form-group form-group-sm">
Project mapping reference:
@Html.DisplayFor(x => x.UniqueMappingReference, Model.UniqueMappingReference)
@Html.HiddenFor(x => x.ProjectUid, Model.ProjectUid)
</div>
<hr />
<div class="row">
<div class="form-group col-md-3">
<label asp-for="SerialNumbers"></label>
@Html.DropDownListFor(x => x.SelectedLoggerId, Model.SerialNumbers, new { @class = "form-control form-control-sm" })
</div>
<div class="form-group col-md-3">
<label asp-for="DateTimeFrom"></label>
@Html.TextBoxFor(m => m.DateTimeFrom, "{0:yyyy-MM-ddTHH:mm}", new { @class = "form-control form-control-sm", type = "datetime-local", @id = "dateFrom", Name = "dateFrom" })
</div>
<div class="form-group col-md-3">
<label asp-for="DateTimeTo"></label>
@Html.TextBoxFor(m => m.DateTimeTo, "{0:yyyy-MM-ddTHH:mm}", new { @class = "form-control form-control-sm", type = "datetime-local", @id = "dateTo", Name = "dateTo" })
</div>
</div>
@Html.Raw(ViewBag.HtmlStr)
</div>
</div>
<input type="button" formmethod="post" value="Draw Chart" id="btnSubmit" name="btnSubmit" class="btn btn-sm btn-primary" />
</div>
</div>
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
Может кто-нибудь сказать мне, почему высотаграфик продолжает непрерывно расти в высоту.