最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Chart.js not height responsive - Stack Overflow

programmeradmin3浏览0评论

I have issues to get the chart.js line chart to be responsive on the height as well as the width.

See example what it should be working like:

  • .html

Here is my code:

  var randomScalingFactor = function(){ return Math.round(Math.random()*100)};
  var lineChartData = {
    labels : ['January','February','March','April','May','June','July'],
    datasets : [
      {
        label: 'My First dataset',
        labelColor : '#fff',
        fontColor : '#fff' ,
        backgroundColor : 'rgba(220,220,220,0.2)',
        borderColor : 'rgba(220,220,220,1)',
        pointBackgroundColor : 'rgba(220,220,220,1)',
        pointBorderColor : '#fff',
        data : [randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor()]
      }
    ]
  }

  var options = {
    maintainAspectRatio: false,
    legend: {
      display: false,
    },
    scales: {
      xAxes: [{
        gridLines: {
         display: false,
         color: '#03A5C5',
         lineWidth: 8,
         },
        ticks: {
          fontColor: "white",
        },
      }],
      yAxes: [{
        gridLines: {
         display: false,
         color: '#03A5C5',
         lineWidth: 8,
         },
        ticks: {
          fontColor: "white",
          beginAtZero: true,
        }
      }]
    }
  };
  var ctx = document.getElementById('canvas-1');
  var chart = new Chart(ctx, {
    responsive: true,
    type: 'line',
    data: lineChartData,
    options: options
  });

I have issues to get the chart.js line chart to be responsive on the height as well as the width.

See example what it should be working like:

  • http://www.chartjs.org/samples/latest/charts/line/basic.html

Here is my code:

  var randomScalingFactor = function(){ return Math.round(Math.random()*100)};
  var lineChartData = {
    labels : ['January','February','March','April','May','June','July'],
    datasets : [
      {
        label: 'My First dataset',
        labelColor : '#fff',
        fontColor : '#fff' ,
        backgroundColor : 'rgba(220,220,220,0.2)',
        borderColor : 'rgba(220,220,220,1)',
        pointBackgroundColor : 'rgba(220,220,220,1)',
        pointBorderColor : '#fff',
        data : [randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor()]
      }
    ]
  }

  var options = {
    maintainAspectRatio: false,
    legend: {
      display: false,
    },
    scales: {
      xAxes: [{
        gridLines: {
         display: false,
         color: '#03A5C5',
         lineWidth: 8,
         },
        ticks: {
          fontColor: "white",
        },
      }],
      yAxes: [{
        gridLines: {
         display: false,
         color: '#03A5C5',
         lineWidth: 8,
         },
        ticks: {
          fontColor: "white",
          beginAtZero: true,
        }
      }]
    }
  };
  var ctx = document.getElementById('canvas-1');
  var chart = new Chart(ctx, {
    responsive: true,
    type: 'line',
    data: lineChartData,
    options: options
  });
Share Improve this question edited May 14, 2021 at 20:40 Sylhare 7,0598 gold badges72 silver badges87 bronze badges asked Aug 3, 2017 at 13:15 Kévin BrunKévin Brun 831 gold badge1 silver badge3 bronze badges 3
  • They are saying in the docs that charts have troubles with being responsive. Hope you'll find the solution because I couldn't – Andrew Commented Aug 3, 2017 at 13:18
  • In docs they recommend to wrap canvas tag into container div and set it it's own width and height. Basically that's how it is done in their responsive expample your mentioned. Will it help to solve your case? – Andrew Commented Aug 3, 2017 at 13:29
  • @blewherself it worked! thanks – Kévin Brun Commented Aug 3, 2017 at 13:46
Add a comment  | 

3 Answers 3

Reset to default 16
  1. Create Class
.chart-container {
    position: relative;
    margin: auto;
    height: 80vh;
    width: 80vw;
}
  1. Create Div With class chart-container and place canvas tag inside it.
<div class="chart-container">
  <canvas id="canvas"></canvas>
</div>
  1. Chart options, use property maintainAspectRatio set to false:
options: {
    maintainAspectRatio: false,
    responsive: true,  
    ...
}

As from Docs for Chart.js it's recommended to wrap canvas into container div and change width/height of the container. But basically it's changing either by given width or height.

Found a more flexible custom solution from lannymcnie that can be used for any canvas responsiveness:

var stage = new createjs.Stage("canvas");

var c = new createjs.Shape();
c.graphics.f("#f00").dc(0,0,50); // Drawn a 100x100 circle from the center

var t = new createjs.Text("Resize the browser/frame to redraw", "24px Arial bold", "#000");
t.x = t.y = 20;
stage.addChild(c, t);

window.addEventListener("resize", handleResize);
function handleResize() {
    var w = window.innerWidth-2; // -2 accounts for the border
    var h = window.innerHeight-2;
    stage.canvas.width = w;
    stage.canvas.height = h;
    //
    var ratio = 100/100; // 100 is the width and height of the circle content.
    var windowRatio = w/h;
    var scale = w/100;
    if (windowRatio > ratio) {
        scale = h/100;
    }
    // Scale up to fit width or height
    c.scaleX= c.scaleY = scale; 
    
    // Center the shape
    c.x = w / 2;
    c.y = h / 2;
        
    stage.update();
}
       
handleResize(); // First draw
html, body {
    padding: 0; margin: 0;
    overflow:hidden;
}
canvas {
    border: 1px solid #f00;
}
<script src="https://code.createjs.com/easeljs-0.8.2.min.js"></script>
<canvas id="canvas" width="800" height="600"></canvas>

You can have it responsive and set a different aspect ratio. My issue was that the chart tend to be squeezed on mobile device taking barely no height.

To remedy, with chart.js 3.2.1, I am using the AspectRatio option:

options: {          
   aspectRatio: 1, 
}

This way the chart is square and stay square, you can play with this number usually between 0.5 to 2 to find a ratio that suits you on both displays.

发布评论

评论列表(0)

  1. 暂无评论