在这个可拖动的 ChartJS 演示中是否可以沿着 ChartJS 绘制的一条曲线导出一组插值坐标?
var options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
fill: true,
tension: 0.4,
borderWidth: 1,
pointHitRadius: 25
},
{
label: '# of Points',
data: [7, 11, 5, 8, 3, 7],
fill: true,
tension: 0.4,
borderWidth: 1,
pointHitRadius: 25
}
]
},
options: {
scales: {
y: {
min: 0,
max: 20
}
},
onHover: function(e) {
const point = e.chart.getElementsAtEventForMode(e, 'nearest', { intersect: true }, false)
if (point.length) e.native.target.style.cursor = 'grab'
else e.native.target.style.cursor = 'default'
},
plugins: {
dragData: {
round: 1,
showTooltip: true,
onDragStart: function(e, datasetIndex, index, value) {
// console.log(e)
},
onDrag: function(e, datasetIndex, index, value) {
e.target.style.cursor = 'grabbing'
// console.log(e, datasetIndex, index, value)
},
onDragEnd: function(e, datasetIndex, index, value) {
e.target.style.cursor = 'default'
// console.log(datasetIndex, index, value)
},
}
}
}
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
window.test = new Chart(ctx, options);
<head>
<meta charset="utf-8">
<title>Chart.js Drag Data Points Plugin</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.0/chart.min.js"></script>
<script src="assets/chartjs-plugin-dragdata.min.js"></script>
<style>
html,
body {
margin: 0;
padding: 0;
}
canvas {
background-color: #eee;
position: absolute;
}
</style>
</head>
<canvas id="chartJSContainer" style="height: 90%; width: 90%;"></canvas>
该演示绘制了包含 5 个值的数组。
data: [12, 19, 3, 5, 2, 3],
有没有办法使用 Javascript 生成一个包含 10 个 y 值的数组,其中 x 坐标沿曲线均匀分布?
例如,如果画布宽度为 200px,则 x 坐标将以
20px
的值递增,y 值将是贝塞尔曲线上的对应点。
我浏览了 ChartJS API 文档,我没有看到每个公开的图的贝塞尔曲线函数的 API,但也许有办法解决这个问题?
根据您想要使用它的目的,一个简单的解决方法/解决方案是:
["Red", "Blue", "Yellow", "Green", "Purple", "Orange", "Blue", "Yellow", "Green", "Purple", "Green"]
labels
数组大小,就像这样 [7, null, 11, null, 5 , null, 8, null, 3, null, 7]
spanGaps: true
属性,以便图表连接点。像这样的chartjs,填补空白,您可以在不手动计算任何额外值的情况下分隔图表。
小演示:
var options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange", "Blue", "Yellow", "Green", "Purple", "Green"],
datasets: [
{
label: '# of Points',
data: [7, null, 11, null, 5 , null, 8, null, 3, null, 7],
fill: true,
tension: 0.4,
borderWidth: 1,
pointHitRadius: 25,
spanGaps: true
}
]
},
options: {
scales: {
y: {
min: 0,
max: 20
}
},
}
}
let ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
html, body { margin: 0; padding: 0;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.0/chart.min.js"></script>
<canvas id="chartJSContainer" style="height: 180px; width: 500px;"></canvas>