gpt4 book ai didi

javascript - 如何仅当文本适合 Chart.Js 2.8.0 中的弧线时才显示文本?

转载 作者:行者123 更新时间:2023-11-29 20:40:43 26 4
gpt4 key购买 nike

我在 Chart.Js 中有一个圆环图与 chartjs-plugin-datalabels启用。只有当字符串适合图表的段时,我如何才能将字符串写入段?

目前,我的代码如下所示:

let ctx = document.getElementById("myChart");
let myChart = new Chart(ctx, {
plugins: [ChartDataLabels],
type: 'doughnut',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 0.3, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
plugins: {
datalabels: {
formatter: function(value) {
return value + " kWh";
}
}
},
rotation: 1 * Math.PI,
circumference: 1 * Math.PI
}
});
<body>
<canvas id="myChart" width="400" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@0.6.0"></script>
</body>

下图显示了我的问题: enter image description here

最佳答案

这可能行得通吗?仅当值高于某个阈值时才添加标签?

let data = [12, 19, 3, 5, 0.3, 3];
let sum = 0;

for (var i = 0; i < data.length; i++) {
sum += data[i]
}

let ctx = document.getElementById("myChart");
let myChart = new Chart(ctx, {
plugins: [ChartDataLabels],
type: 'doughnut',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: data,
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
plugins: {
datalabels: {
formatter: function(value) {
percentage = (value / sum) * 100;
if (percentage < 1) {
return "";
}
return value + " kWh";
}
}
},
rotation: 1 * Math.PI,
circumference: 1 * Math.PI
}
});
<body>
<canvas id="myChart" width="400" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@0.6.0"></script>
</body>

关于javascript - 如何仅当文本适合 Chart.Js 2.8.0 中的弧线时才显示文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55586373/

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