问题描述
我正在创建一个包含两个甜甜圈图的JavaScript网页。创建一个图表,我正在使用一个函数,并为每个图表使用不同的数据调用两次。但是,当我这样做时,甜甜圈图中间的文本不仅针对当前图表被更改为两个图表。我该如何分别为每个文本写文字? 这是我的代码
function chart(dummynames,dummyValues,dummyColors,percentage,id) {
//dummy names,dummy values and dummy colors are arrays
new Chart(document.getElementById(id),{
type: 'doughnut',data: {
labels: dummynames,datasets: [{
label: "tessers",backgroundColor: dummyColors,data: dummyValues,}]
},options: {
title: {
display: true,align: 'center',horizontalAlign: "center",verticalAlign: "bottom",dockInsidePlotArea: true
},legend: {
display: false
},cutoutPercentage: 70,},});
Chart.pluginService.register({
beforeDraw: function(chart) {
var width = chart.chart.width,height = chart.chart.height + 35,ctx = chart.chart.ctx;
ctx.restore();
var fontSize = (height / 200).toFixed(2);
ctx.font = fontSize + "em sans-serif";
ctx.textBaseline = "middle";
var text = percentage,textx = Math.round((width - ctx.measureText(text).width) / 2),textY = height / 2;
ctx.fillText(text,textx,textY);
ctx.save();
}
})
}
解决方法
您应该将Chart.pluginService.register
放在chart
函数之外,以确保仅被调用一次。
请查看修改后的代码,并查看其工作原理。
Chart.pluginService.register({
beforeDraw: function(chart) {
var width = chart.chart.width,height = chart.chart.height + 35,ctx = chart.chart.ctx;
ctx.save();
var fontSize = (height / 200).toFixed(2);
ctx.font = fontSize + "em sans-serif";
ctx.textBaseline = "middle";
var text = chart.data.datasets[0].percentage,textX = Math.round((width - ctx.measureText(text).width) / 2),textY = height / 2;
ctx.fillText(text,textX,textY);
ctx.restore();
}
});
function chart(dummynames,dummyValues,dummyColors,percentage,id) {
new Chart(document.getElementById(id),{
type: 'doughnut',data: {
labels: dummynames,datasets: [{
label: "tessers",backgroundColor: dummyColors,data: dummyValues,percentage: percentage
}]
},options: {
title: {
display: true,align: 'center',horizontalAlign: "center",verticalAlign: "bottom",dockInsidePlotArea: true
},legend: {
display: false
},cutoutPercentage: 70,},});
}
chart(['A','B'],[5,6],['red','blue'],'26.846%','myChart1');
chart(['X','Y'],[7,5],['green','purple'],'19.451%','myChart2');
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<div style="display: flex">
<div>
<canvas id="myChart1"></canvas>
</div>
<div>
<canvas id="myChart2"></canvas>
</div>
</div>