0
votes

Im trying to learn a charting library in javascript and came across chart.js

Ive just copied the code from their installation front page as shown below.

My question is, why does changing the height and width parameters in the canvas element tag not actually change the size of the chart?

I believe this is explained on chart js's website "Detecting when the canvas size changes can not be done directly from the canvas element. Chart.js uses its parent container to update the canvas render and display sizes. However, this method requires the container to be relatively positioned and dedicated to the chart canvas only. Responsiveness can then be achieved by setting relative values for the container size (example):".

However I do not understand what container they are referring to as parent container as I cant find anything Ive specified in my code that could be referred to as parent container (pretty new to html, css and js).

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
        datasets: [{
            label: '# of Votes',
            data: [12, 19, 3, 5, 2, 3],
            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
            }
        }
    }
});
<!DOCTYPE html>
<html>
<head>
    <title>test</title>
</head>
<body>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/Chart.min.js"></script>
    <canvas id="myChart" width="400" height="400"></canvas>
    <script type="text/javascript" src="script.js"></script>
</body>
</html>
1

1 Answers

0
votes

This issue you have here is that chartJS will ignore the width / height on the canvas element, so you need to wrap the canvas element in a div.....

<div style="width:400px;height:600px">
    <canvas id="myChart"></canvas>
</div>