| 1 |
/* Bar Chart — frontend.js (Chart.js via CDN) */ |
| 2 |
( function () { |
| 3 |
var CHARTJS_CDN = 'https://cdn.jsdelivr.net/npm/chart.js@4.4.3/dist/chart.umd.min.js'; |
| 4 |
|
| 5 |
function loadChartJs(cb) { |
| 6 |
if (window.Chart) { cb(); return; } |
| 7 |
var s=document.createElement('script'); s.src=CHARTJS_CDN; s.onload=cb; document.head.appendChild(s); |
| 8 |
} |
| 9 |
|
| 10 |
function hexToRgb(hex) { |
| 11 |
return parseInt(hex.slice(1,3),16)+','+parseInt(hex.slice(3,5),16)+','+parseInt(hex.slice(5,7),16); |
| 12 |
} |
| 13 |
|
| 14 |
function initChart(wrap) { |
| 15 |
var canvas = wrap.querySelector('canvas'); |
| 16 |
if (!canvas) return; |
| 17 |
var labels = (wrap.dataset.labels||'').split(',').map(s=>s.trim()); |
| 18 |
var datasets = JSON.parse(wrap.dataset.datasets||'[]'); |
| 19 |
var orient = wrap.dataset.orientation==='horizontal'; |
| 20 |
var stacked = wrap.dataset.stacked==='1'; |
| 21 |
var barRadius = parseInt(wrap.dataset.barRadius)||0; |
| 22 |
var height = parseInt(wrap.dataset.height)||340; |
| 23 |
var showGrid = wrap.dataset.grid!=='0'; |
| 24 |
var showLeg = wrap.dataset.legend!=='0'; |
| 25 |
var legPos = wrap.dataset.legendPos||'top'; |
| 26 |
|
| 27 |
canvas.height = height; |
| 28 |
|
| 29 |
var chartDatasets = datasets.map(function(ds) { |
| 30 |
var rgb=hexToRgb(ds.color||'#6c3fb5'); |
| 31 |
return { |
| 32 |
label: ds.label, |
| 33 |
data: (ds.data||'').split(',').map(Number), |
| 34 |
backgroundColor: 'rgba('+rgb+',0.82)', |
| 35 |
borderColor: ds.color, |
| 36 |
borderWidth: 1, |
| 37 |
borderRadius: barRadius, |
| 38 |
borderSkipped: false, |
| 39 |
}; |
| 40 |
}); |
| 41 |
|
| 42 |
new window.Chart(canvas,{ |
| 43 |
type: orient ? 'bar' : 'bar', |
| 44 |
data: {labels:labels,datasets:chartDatasets}, |
| 45 |
options:{ |
| 46 |
indexAxis: orient ? 'y' : 'x', |
| 47 |
responsive:true, |
| 48 |
plugins:{legend:{display:showLeg,position:legPos}}, |
| 49 |
scales:{ |
| 50 |
x:{stacked:stacked,grid:{display:showGrid}}, |
| 51 |
y:{stacked:stacked,grid:{display:showGrid}}, |
| 52 |
}, |
| 53 |
} |
| 54 |
}); |
| 55 |
} |
| 56 |
|
| 57 |
function init(){ |
| 58 |
var wraps=document.querySelectorAll('.bkbc-wrap[data-type]'); |
| 59 |
if(!wraps.length) return; |
| 60 |
loadChartJs(function(){ wraps.forEach(initChart); }); |
| 61 |
} |
| 62 |
if(document.readyState==='loading') document.addEventListener('DOMContentLoaded',init); |
| 63 |
else init(); |
| 64 |
}() ); |
| 65 |
|