Chart.js页面首次加载不显示图表,调试/多次刷新才显示求助
Hey there, let's figure out why your bar chart is only showing up after refreshing or inspecting elements—this is a common issue with Chart.js, usually tied to DOM timing or container sizing. Here are the most likely fixes tailored to your code:
1. Ensure Your Code Runs After the DOM is Fully Loaded
Right now, your script might be executing before the <canvas id="barChart"> element is rendered in the DOM. That means $("#barChart").get(0) could return null on first load, breaking the chart initialization entirely.
Wrap your entire chart code in jQuery's ready handler to delay execution until the DOM is fully ready:
$(function() { // Your entire chart code goes here var barChartCanvas = $("#barChart").get(0).getContext("2d"); var barChart = new Chart(barChartCanvas); var barChartData = { labels: <?= json_encode($WEEK_NOS); ?>, datasets: [ { label: "Packing Target", fillColor: "rgba(210, 214, 222, 1)", strokeColor: "rgba(210, 214, 222, 1)", pointColor: "rgba(210, 214, 222, 1)", pointStrokeColor: "#c1c7d1", pointHighlightFill: "#fff", pointHighlightStroke: "rgba(220,220,220,1)", data: <?= json_encode($PACKING_TARGET); ?> }, { label: "Fabric Despatch", fillColor: "rgba(0, 255, 0, 1)", strokeColor: "rgba(210, 214, 222, 1)", pointColor: "rgba(210, 214, 222, 1)", pointStrokeColor: "#c1c7d1", pointHighlightFill: "#fff", pointHighlightStroke: "rgba(220,220,220,1)", data: <?= json_encode($SM_OGP_MTRS); ?> }, { label: "Remaining", fillColor: "rgba(214, 0, 22, 122)", strokeColor: "rgba(210, 214, 222, 1)", pointColor: "rgba(210, 214, 222, 1)", pointStrokeColor: "#c1c7d1", pointHighlightFill: "#fff", pointHighlightStroke: "rgba(220,220,220,1)", data: <?= json_encode($REMAINING); ?> } ] }; var barChartOptions = { scaleBeginAtZero: true, scaleShowGridLines: true, scaleGridLineColor: "rgba(0,0,0,.05)", scaleGridLineWidth: 1, scaleShowHorizontalLines: true, scaleShowVerticalLines: true, barShowStroke: true, barStrokeWidth: 2, barValueSpacing: 5, barDatasetSpacing: 1, legendTemplate: "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].fillColor%>\"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>", multiTooltipTemplate: "<%= datasetLabel %> - <%= value %>", responsive: true, maintainAspectRatio: true }; barChart.Bar(barChartData, barChartOptions); // Your tooltip function and other code function showTooltip(x, y, contents) { $('<div id="tooltip" class="tooltip top in"><div class="tooltip-inner">' + contents + '<\/div><\/div>').css({ display: 'none', top: y - 40, left: x - 55, }).appendTo("body").fadeIn(200); } $(".flot-x-axis.flot-x1-axis.xAxis.x1Axis").find(".flot-tick-label.tickLabel").hide() });
2. Add Explicit Dimensions to Your Canvas Container
Chart.js relies on the canvas element (or its parent container) having defined width/height to calculate the chart size correctly. If the container has no explicit dimensions, the browser might skip rendering it on first load (inspecting elements triggers a layout reflow, which fixes this).
Add CSS to your #barChart element:
#barChart { width: 100% !important; height: 400px !important; }
Or set dimensions directly on the canvas tag:
<canvas id="barChart" width="800" height="400"></canvas>
3. Verify Your Backend Data is Loading Correctly
Your code uses <?= json_encode(...) ?> to pass backend data to the chart. If the PHP variables are empty or not initialized when the script runs, the chart will have no data to display.
Add console logs to check if your data is being output correctly:
$(function() { // Log data to validate it's being passed properly console.log("Week Numbers:", <?= json_encode($WEEK_NOS); ?>); console.log("Packing Target Data:", <?= json_encode($PACKING_TARGET); ?>); console.log("Remaining Data:", <?= json_encode($REMAINING); ?>); // Rest of your chart code... });
Open your browser's dev tools (F12) and check the Console tab—if any of these are undefined or empty, you'll need to fix your backend logic to ensure the variables are populated before rendering the script.
4. Force a Chart Redraw After Initialization
Sometimes, even with the above fixes, layout delays can prevent the chart from rendering. You can force a redraw by triggering a resize event after initialization:
// Add this right after barChart.Bar(barChartData, barChartOptions); setTimeout(function() { $(window).trigger('resize'); }, 100);
This gives the browser a moment to finish layout before redrawing the chart.
Quick Debugging Tip
If none of the above work, check the Console tab in your browser's dev tools for errors—this will often point you to the exact issue (e.g., missing variables, invalid Chart.js syntax).
内容的提问来源于stack exchange,提问作者Moaiz Pervaiz

