chartjs-plugin-doughnutlabel-v3
Version:
Chart.js (Version 3) Doughnut Chart plugin to display custom lines of text in the center of the donut.
2 lines (1 loc) • 2.28 kB
JavaScript
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e(require("chart.js"),require("chart.js/helpers")):"function"==typeof define&&define.amd?define(["chart.js","chart.js/helpers"],e):(t="undefined"!=typeof globalThis?globalThis:t||self)["chartjs-plugin-doughnutlabel"]=e(t.Chart,t.Chart.helpers)}(this,(function(t,e){"use strict";const n={parseText:(t,e)=>"function"==typeof t?t(e):t,parseFont:o=>{const l=t.Chart.defaults,i=e.valueOrDefault(o.size,l.font.size),r={family:e.valueOrDefault(o.family,l.font.family),lineHeight:e.toLineHeight(o.lineHeight,i),size:i,style:e.valueOrDefault(o.style,l.font.style),weight:e.valueOrDefault(o.weight,null),string:""};return r.string=n.toFontString(r),r},toFontString:t=>!t||e.isNullOrUndef(t.size)||e.isNullOrUndef(t.family)?"":(t.style?t.style+" ":"")+(t.weight?t.weight+" ":"")+t.size+"px "+t.family,textSize:(t,e)=>{const{ctx:n}=t,o=n.font;let l=0,i=0;e.forEach((e=>{const o="function"==typeof e.text?e.text(t):e.text;n.font=e.font?e.font.string:"",l=Math.max(n.measureText(o).width,l),i+=e.font.lineHeight})),n.font=o;return{height:i,width:l}}};var o={id:"doughnutLabel",defaults:{font:{family:"sans-serif",size:16,style:"normal",weight:"normal",lineHeight:1.2,string:"16px sans-serif"}},beforeDraw:(o,l,i)=>((o,l)=>{if(o.chartArea&&l){const{labels:i}=l;if(!i?.length)return;const{ctx:r,chartArea:{top:s,right:f,bottom:a,left:h}}=o,u=[];i.forEach((i=>{const s={text:n.parseText(i.text,o),font:n.parseFont(e.resolve([i.font,l.font,t.Chart.defaults.font],r,0)||t.Chart.defaults.font),color:e.resolve([i.color,l.color,t.Chart.defaults.color],r,0)??"#000"};u.push(s)}));let c=n.textSize(o,u);const g=Math.sqrt(Math.pow(c.width,2)+Math.pow(c.height,2)),d=2*t.DoughnutController.prototype.innerRadius/g;d<1&&(u.forEach((o=>{o.font.size=Math.floor(o.font.size*d),o.font.lineHeight=1.2,o.font=n.parseFont(e.resolve([o.font,null],r,0)||t.Chart.defaults.font)})),c=n.textSize(o,u)),r.textAlign="center",r.textBaseline="middle";const p=(h+f)/2,x=(s+a)/2-c.height/2;let y;const m=u.length;let w=0;for(y=0;y<m;++y){r.fillStyle=u[y].color,r.font=u[y].font.string;const t=x+u[y].font.lineHeight/2+w;w+=u[y].font.lineHeight;const e=n.parseText(u[y].text,o);r.fillText(e,p,t)}}})(o,i)};return t.Chart.register(o),o}));