[Chartjs]-Chart.js chart distorted with fixed width

3👍

for me the problem was that graph was setting for itself height that was bigger that I myself had set to canvas.

my solution was:

  1. I removed all height setups for canvas (css and tag attribute)
  2. Created container tag for the canvas and set height to it
  3. in chart options added:
      responsive: true,
      maintainAspectRatio: false,

in the example in the question problem was in css:

canvas {
  left: 0px;
  height: 300px !important;
}

i would change it to:

.tds-hor-scroll {
	overflow-x: auto;
}
.tds-chart-inner {
  min-width: 850px;
  height: 300px;
}
<div class="tds-hor-scroll">
	<div class="tds-chart-inner">
	  <canvas id="tds-chart-mem"></canvas>
	</div>
</div>

1👍

<!DOCTYPE HTML>
<html lang="en">

<head>
<meta charset="utf-8">
<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport" />

<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />


</head>

<style>
 .tds-chart-inner {
  width:100%;
 }


</style>

<body class="">

<div class="tds-chart-inner tds-hor-scroll">
 <canvas id="myChart"></canvas>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.min.js"> 
</script>


<script>
 var ctx = document.getElementById("myChart").getContext('2d');
 var myChart = new Chart(ctx, {
 type: 'line',
 data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3,80],
        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: {
        yAxes: [{
            ticks: {
                beginAtZero:true,
                fontColor: 'red'
            }
        }]
    }
}
});



</script>   

Leave a comment