gpt4 book ai didi

javascript - Chart js - 渲染后获取条形宽度

转载 作者:行者123 更新时间:2023-12-01 15:22:15 25 4
gpt4 key购买 nike

我需要以像素为单位获取条形宽度并将其用于 pointRadius: {{barwidth}} 的图表 js 设置中的重叠折线图。我的图表也设置为响应式,因此如果要调整窗口大小,我需要更新此值。

我很难过。并且真的可以使用一些帮助。

查看每个条上的线



这是带有pointStyle: 'line' 的折线图设置所以我可以有这个效果。现在我需要用 pointRadius: {{barwidth}} 将该线的宽度设置为条形。

最佳答案

通常你可以使用 getDatasetMeta() 图表的方法来获取条形宽度。

但是,如果您要动态更改/更新折线图的点半径(在调整窗口大小时),则必须使用图表插件,如下所示:

Chart.plugins.register({
updated: false,
beforeDraw: function(chart) {
var barWidth = chart.getDatasetMeta(1).data[0]._model.width;
var line = chart.data.datasets[0];
line.pointRadius = barWidth / 2;
line.pointHoverRadius = barWidth / 2;
if (!this.updated) {
chart.update();
this.updated = true;
}
}
});

* 在脚本的开头添加这个

ᴅᴇᴍᴏ ⧩

Chart.plugins.register({
updated: false,
beforeDraw: function(chart) {
var barWidth = chart.getDatasetMeta(1 /* dataset-index of bar graph */).data[0]._model.width;
var line = chart.data.datasets[0 /* dataset-index of line graph */];
line.pointRadius = barWidth / 2;
line.pointHoverRadius = barWidth / 2;
// update chart at first render with newly added values
if (!this.updated) {
chart.update();
this.updated = true;
}
}
});

var chart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
datasets: [{
type: 'line',
label: 'LINE',
data: [3, 1, 4, 2, 5],
backgroundColor: 'rgba(0, 119, 290, 0.5)',
borderColor: 'transparent',
pointBorderColor: '#07C',
fill: false,
pointStyle: 'line'
}, {
label: 'BAR',
data: [3, 1, 4, 2, 5],
backgroundColor: 'rgba(4, 142, 128, 0.5)'
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="ctx"></canvas>

关于javascript - Chart js - 渲染后获取条形宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45707618/

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