<!DOCTYPE html>
<
html
lang
=
"en"
>
<
head
>
<
meta
charset
=
"UTF-8"
>
<
title
>Chart.js Bar Chart Example</
title
>
<
script
src
=
</
script
>
</
head
>
<
body
>
<
canvas
id
=
"myBarChart"
width
=
"600"
height
=
"300"
>
</
canvas
>
<
button
id
=
"recreateChart"
>
Recreate Chart
</
button
>
<
script
>
// JavaScript code will be here
let myBarChart;
// Global variable to
// hold the chart instance
// Function to create a chart
function createChart(dataArray) {
const ctx = document
.getElementById('myBarChart')
.getContext('2d');
myBarChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Red',
'Blue',
'Yellow',
'Green',
'Purple',
'Orange'],
datasets: [{
label: 'Votes',
data: dataArray,
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: {
scales: {
y: {
beginAtZero: true
}
}
}
});
}
// Initial chart creation
createChart([12, 19, 3, 5, 2, 3]);
// Event listener for the button
document.getElementById('recreateChart')
.addEventListener('click', function () {
// Destroy the existing
// chart if it exists
if (myBarChart) {
myBarChart.destroy();
}
// Recreate the chart
// with new random data
const newData = Array.from({ length: 6 },
() => Math.floor(Math.random() * 20));
createChart(newData);
});
</
script
>
</
body
>
</
html
>