image.png
在開發(fā)的過程中接到這樣一個需求子房,需要畫出如上圖的一個柱狀圖形用,難點就在于分類lable的實現(xiàn)。
本來打算使用div或者table來進行計算和布局证杭,但是要和原有圖表連在一起田度,所以不是很方便,于是決定用canvas來做解愤。
在畫線的時候發(fā)現(xiàn)了一個很坑爹的地方镇饺,就是畫出來的線比較細,顏色也比較淺送讲,于是去看看echarts怎么做的奸笤,發(fā)現(xiàn)echarts的canvas實例是將canvas畫布放大至容器的二倍,但是樣式還是以容器的寬高為主哼鬓,這樣就加重了線條监右,經(jīng)過測試果然是可行的。
另外一點就是canvas畫線的位置是以一個像素點的中間線上下各取0.5像素來畫線條异希,所以在處理線條的時候我們一般會加上0.5像素來畫起始點健盒,兩倍就是加上一個像素。
總體思路就是在echarts的容器上再畫一個canvas称簿,然后設(shè)置z-index比echarts的小味榛,之后就是數(shù)學(xué)方面的計算了。
附上關(guān)鍵代碼
function addCanvas(el) {
let canvas = document.createElement('canvas');
let width = el.offsetWidth;
let height = el.offsetHeight;
canvas.width = width * 2;
canvas.height = height * 2;
canvas.style = `position:absolute;top:0;left:0;width:${width}px;height:${height}px;z-index:-1`;
el.appendChild(canvas);
return {
context: canvas.getContext('2d'),
width: width * 2,
height: height * 2,
};
}
/**
*
* @param {*} echartsInstance eCharts實例
* @param {*} baseLineBottom 分類基線距離echarts容器高度
* @param {*} tickRates 每條分割線所占的位置
* @param {*} names 每一個類別的名稱
*/
function splitArea(echartsInstance, baseLineBottom, tickRates, names) {
let option = echartsInstance.getOption();
let { context, width, height } = addCanvas(echartsInstance.getDom());
let { left, right, bottom } = option.grid[0];
let start, end, tickLength;
if (typeof left === 'number') {
start = left * 2 + 1;
} else {
start = (parseFloat(left) / 100) * width + 1;
}
if (typeof right === 'number') {
end = width - right * 2 + 1;
} else {
end = width - (parseFloat(left) / 100) * width + 1;
}
if (typeof bottom === 'number') {
tickLength = bottom * 2 - baseLineBottom * 2;
} else {
tickLength = (parseFloat(bottom) / 100) * height - baseLineBottom * 2;
}
context.strokeStyle = 'black';
context.lineWidth = 2;
context.font = '24px Arial';
context.beginPath();
// context.moveTo(start, height - baseLineBottom * 2);
// context.lineTo(end, height - baseLineBottom * 2);
tickRates.forEach((item, index) => {
console.log(start + (end - start) * item);
context.moveTo(start + (end - start) * item, height - baseLineBottom * 2);
context.lineTo(start + (end - start) * item, height - baseLineBottom * 2 - tickLength);
if (index !== 0) {
let fontWidth = context.measureText(names[index - 1]).width;
context.fillText(
names[index - 1],
start +
(tickRates[index - 1] + (item - tickRates[index - 1]) / 2) * (end - start) -
fontWidth / 2,
height - baseLineBottom * 2 - tickLength / 2 + 24,
);
}
});
context.stroke();
}
// 省略了echarts初始化的代碼予跌,調(diào)用示例如下搏色。
splitArea(myChart, 10, [0, 3 / 6, 5 / 6, 1], ['類別一', '類別二', '類別三xxx']);