instructions
I have been using Echars for a long time. It is difficult for me to use Echarts if there is a pie chart of the style shown in the figure above. The official document does not have a pie chart of this mode. I have tried to draw pie charts with D3 and Canvas respectively. Since I am familiar with canvas and D3 also need to introduce plug-ins, in line with the principle of lightweight, CANVAS packaging is adopted.
The official pie chart has two modes :(1) radius mode and (2) area mode
The implementation process
(1) Encapsulated functions are as follows:
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 (letItem of data_arr) {sum += item.value * 1.0} data_arr = data_arr.map((v, I) => {sum += item.value * 1.0} data_arr = data_arr.map((v, I) => {return{name: v.name, value: (v.value) * 1.0 / sum}})for (leti = 0; i < data_arr.length; I++) {// draw the pie chartletmin = (cW > cH ? cH : cW); Agl = data_arr[I]. Value * pi2 + startAgl; Color_arr [I]; color_arr[I]; C.linewidth = data_arr[I]. Value * min * 0.3; C.beinpath (); c.beinpath (); C. rc(cW / 2, cH / 2, min * 0.3, startAgl, AGL,false); / / c.s. troke circle (); 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); }}Copy the code
(2) Call method:
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)Copy the code