說明
我用echars很久了,如果出現如上圖所示樣式的餅圖,我用echarts很難實現,官方給的文件沒有這種模式的餅圖。試過用d3和canvas分別畫餅圖,因為本人對canvas比較熟悉和d3還要引入外掛,本著輕量化的原則,所以採用canvas封裝。
官方餅圖兩種模式:(1)半徑模式(2)面積模式
實現過程
(1)封裝的函式如下:
function drawCircle(canvasId, option) {
const color_arr = option.color
let data_arr = option.data
const pi2 = Math.PI * 2;
let canvas = document.getElementById(canvasId);
let c = canvas.getContext("2d");
let startAgl = 0;
let agl;
let sum = 0;
const cW = canvas.width;
const cH = canvas.height;
for (let item of data_arr) {
sum += item.value * 1.0
}
data_arr = data_arr.map((v, i) => {
return {
name: v.name,
value: (v.value) * 1.0 / sum
}
})
for (let i = 0; i < data_arr.length; i++) {
//繪製餅圖
let min = (cW > cH ? cH : cW); //獲取canvas寬高的最小值
agl = data_arr[i].value * pi2 + startAgl; //終點
c.strokeStyle = color_arr[i];
c.lineWidth = data_arr[i].value * min * 0.3; // 線的粗細
c.beginPath();
c.arc(cW / 2, cH / 2, min * 0.3, startAgl, agl, false); //畫圓
c.stroke();
c.closePath();
startAgl = agl;
//繪製圖例
c.fillStyle = color_arr[i];
c.fillRect(cW * 0.8, 50 + 18 * i, 16, 16);
c.fillText(data_arr[i].name, cW * 0.8 + 20, 62 + 18 * i);
}
}複製程式碼
(2)呼叫方式:
let color = ['#0580F2', '#FAA732', '#E1575D', '#8B73CC', '#8CD123', '#4B53BA', '#429588'];
let option = {
color: color,
data: [
{ name: '20', value: '20' },
{ name: '30', value: '30' },
{ name: '40', value: '40' },
{ name: '50', value: '50' },
{ name: '60', value: '60' },
]
}
drawCircle('myCanvas', option)複製程式碼