Part 1: Why consider Chart.js with Power Pages
Posted on November 12, 2024 (Last modified on November 28, 2024) • 2 min read • 393 wordsWe are going to have a look at how to use open-source library Chart.js. In this first blog it will focus on a simple example and the 2nd blog in the series will present something more complex.
By the end of the example you should have the below bar chart in Power Pages by using Chart.js.
W3Schools provide a great example for us to use, so let’s get started.
Note
As this is straightforward example with not using any liquid etc, this code has been placed in a web page.
Add the CDN link to your HTML web page of your choice.
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
Add the canvas element to where in the HTML you want to display the chart.
<canvas id="myChart" style="width:100%;max-width:700px"></canvas>
Copy the below JS code to your web page JS section.
const xValues = ["Italy", "France", "Spain", "USA", "Argentina"];
const yValues = [55, 49, 44, 24, 15];
const barColors = ["red", "green","blue","orange","brown"];
new Chart("myChart", {
type: "bar",
data: {
labels: xValues,
datasets: [{
backgroundColor: barColors,
data: yValues
}]
},
options: {...}
});
Sync your changes and refresh the cache on your browser and you should be able to view the chart.
Full HTML code below.
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
<div
class="row sectionBlockLayout text-start"
style="min-height: auto; padding: 8px;"
>
<div class="container" style="display: flex; flex-wrap: wrap;">
<div
class="col-lg-12 columnBlockLayout"
style="padding: 16px; margin: 60px 0px; min-height: 200px;"
>
<h1>Out of the box example</h1>
<canvas id="myChart" style="width:100%;max-width:600px"></canvas>
</div>
</div>
</div>
To recap, Chart.js is a great tool and its worth looking into for straightforward charts for Power Pages. If you want build a chart by using data from Dataverse then check out Part 2 of the series.
Have a great day!