传真
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels"></script>
<canvas id="myChart"></canvas>
JS
const ctx = document.getElementById( myChart ).getContext( 2d );
// Create the chart with the plugin and other options
const chart = new Chart(ctx, {
type: bar ,
data: {
labels: [ Label 1 , Label 2 , Label 3 ],
datasets: [{
label: Data ,
data: [10, 20, 30],
backgroundColor: rgba(0, 123, 255, 0.5)
}]
},
options: {
plugins: {
datalabels: {
display: false // Hide the data labels by default
}
},
responsive: true,
maintainAspectRatio: false,
hover: {
onHover: handleHover // Call the handleHover function on hover
}
}
});
// Function to handle the hover effect
function handleHover(activeElements) {
if (activeElements.length > 0) {
const element = activeElements[0];
// Increase border radius and width
element._model.borderWidth += 2;
element._model.borderRadius = 10;
// Display the data labels
chart.options.plugins.datalabels.display = true;
chart.update();
} else {
// Reset styles and hide data labels when not hovering
chart.data.datasets[0].data.forEach((_, index) => {
const element = chart.getDatasetMeta(0).data[index];
element._model.borderWidth = 0;
element._model.borderRadius = 0;
});
chart.options.plugins.datalabels.display = false;
chart.update();
}
}
让我知道,这是否有助于我的朋友工作。