iChart.js 是個相當好用的圖表繪製函式庫。官網有畫平均線的範例,但沒有「虛線」版本,而實務上為了不與資料線混淆,平均線幾乎都會用虛線表示。本文示範如何用自訂元件畫出多張折線圖,並在每張圖上疊加一條虛線平均線。
var Data = new Array();
Data[0] = {
labels: ["第一單元", "第二單元", "第三單元", "第四單元", "第五單元"],
datasets: [{ name: '優秀率', color: '#1dbcfe', line_width: 4, value: [80, 75, 92, 62, 0] }]
};
Data[1] = {
labels: ["第一單元", "第二單元", "第三單元", "第四單元", "第五單元"],
datasets: [{ name: '優秀率', color: '#1dbcfe', line_width: 4, value: [50, 11, 62, 77, 90] }]
};
Data[2] = {
labels: ["第一單元", "第二單元", "第三單元", "第四單元", "第五單元"],
datasets: [{ name: '優秀率', color: '#1dbcfe', line_width: 4, value: [80, 51, 32, 44, 80] }]
};
var _bodyWidth = $('body').width() - 16;
$('.item').each(function (i) {
var _id = $(this).find('.canvas-wrap').attr('id');
var chart = new iChart.LineBasic2D({
render: _id,
data: Data[i].datasets,
align: 'center',
border: 0,
width: _bodyWidth * 2, // 兩倍尺寸,後續用 CSS 縮回,確保行動裝置高清
height: _bodyWidth * 1.2,
background_color: '#fafafa',
animation: true,
animation_duration: 600,
sub_option: {
smooth: true,
hollow: false,
hollow_inside: false,
point_size: 16,
listeners: { parseText: function (r, t) { return t + '%'; } },
label: { fontsize: 24, color: '#333' }
},
coordinate: {
width: _bodyWidth * 1.6,
valid_width: _bodyWidth * 1.4,
height: _bodyWidth * 1.6 * .5,
striped_factor: 0.18,
axis: { color: '#aaa', width: [0, 0, 8, 0] },
scale: [
{
position: 'left', start_scale: 0, end_scale: 100,
scale_space: 20, scale_size: 2, scale_enable: false,
label: { color: '#999', fontsize: 24 }, scale_color: '#999'
},
{
position: 'bottom', scale_enable: false,
label: { color: '#999', fontsize: 24 }, labels: Data[i].labels
}
]
}
});
/**
* 自訂元件:畫平均線(虛線)
*/
chart.plugin(new iChart.Custom({
drawFn: function () {
// 計算平均值的對應 Y 座標
var _total = 0;
$.each(Data[i].datasets[0].value, function (k, val) { _total += val; });
var avg = _total / Data[i].datasets[0].value.length,
coo = chart.getCoordinate(),
x = coo.get('originx'),
W = coo.width,
S = coo.getScale('left'),
H = coo.height,
h = (avg - S.start) * H / S.distance,
y = chart.y + H - h;
// 以固定間距循環畫短線段,湊成虛線
for (var xi = x; xi <= (x + W); xi = xi + 32) {
chart.target.line(xi, y, xi + 16, y, 2, '#fe941c');
}
chart.target.textAlign('start')
.textBaseline('middle')
.textFont('500 20px Verdana')
.fillText('平均戰勝率' + avg + '%', x + W - 100, y - 20, false, '#fe941c');
}
}));
chart.draw();
});
iChart 沒有內建的 dash 樣式設定,所以這裡用了一個變通做法:沿著平均線的 Y 座標,以 32px 為週期畫一段 16px 的線段,畫一段、空一段,視覺上就成為虛線。調整這兩個數字(週期與線長)即可改變虛線的疏密。
Y 座標的算法是:先把 getScale('left') 拿到的起始值與刻度距離取出,再用 (avg - start) * 座標高度 / 刻度總距離 換算成像素偏移,最後從座標原點往回推。這段換算若不清楚,平均線就會畫到圖外。
iChart 在行動裝置上需要先以兩倍尺寸建立畫布,再用 CSS 與 JS 手動縮放回正常範圍,才能維持高解析度、避免模糊。程式中 width: _bodyWidth * 2 與各處 * 1.6 的倍率就是為此而設。
如果有更好的虛線繪製方式,歡迎留言交流。