问题
I have a chart like this:
Now I need to find the minimum and maximum labels that are inside a pan, when I zoom, for example:
The minimum would be 2018-07-16
, and the maximum would be 2018-11-3
.
For panning, I'm using this attribute:
pan: {
enabled: true,
mode: 'x',
onPanComplete: function(e) {
console.log(e)
}
}
If I look at the returned object, I see a lot of information about this pan. But I can't find relevant information to conclude these extremum labels.
I thought the attribute chartArea
would be sufficient, but its value doesn't differ for two very different pans. Same goes for config
, boxes
, and a lot of other attributes.
How can I find these extremum labels?
回答1:
I assume you're using chartjs-plugin-zoom for this.
Digging around in the chart
object passed to the onPanComplete
function reveals that the scales
property is updated to achieve the zoom'n'pan functionality. Knowing this, it's fairly trivial to retrieve the first and last tick objects which contain the label
property you're looking for.
Below is a snippet that demonstrates accessing the ticks via onPanComplete
and outputting them to the page:
let ft = document.getElementById("ft"),
lt = document.getElementById("lt");
new Chart(document.getElementById("chart"), {
type: "line",
data: {
labels: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'],
datasets: [{
data: [0, 1, 2, 4, 8, 16, 32, 64, 128, 256]
}]
},
options: {
maintainAspectRatio: false,
scales: {
xAxes: [{
ticks: {
min: 'c',
max: 'h'
}
}]
},
plugins: {
zoom: {
pan: {
enabled: true,
mode: 'x',
onPanComplete: function({
chart
}) {
let ticks = chart.scales["x-axis-0"]._ticks;
ft.innerText = JSON.stringify(ticks[0]);
lt.innerText = JSON.stringify(ticks[ticks.length - 1]);
}
}
}
}
}
});
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.1"></script>
<script src="https://cdn.jsdelivr.net/npm/hammerjs@2.0.8"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-zoom@0.7.4"></script>
<canvas id="chart" style="max-height:125px"></canvas>
<p>
First tick: <span id="ft"></span><br>Last tick: <span id="lt"></span>
</p>
来源:https://stackoverflow.com/questions/58352678/chartjs-finding-the-minimum-and-maximum-labels-that-are-inside-a-pan-when-zoo