gpt4 book ai didi

javascript - 我如何为图表 js 使用内联插件内部标题?

转载 作者:行者123 更新时间:2023-12-04 16:12:34 25 4
gpt4 key购买 nike

我正在创建一个带有两个圆环图的 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();
}
})
}
enter image description here

最佳答案

您应该放置 Chart.pluginService.registerchart函数,从而确保它只被调用一次。
请查看您修改后的代码,看看它是如何工作的。

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>

关于javascript - 我如何为图表 js 使用内联插件内部标题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64567538/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com