Charts.js graph not scaling to canvas size

后端 未结 11 1142
隐瞒了意图╮
隐瞒了意图╮ 2020-12-08 09:45

I\'m trying to make a graph with Charts.js (current one is just a really simple example I\'m trying to get working, somewhat taken from the Chart.js documentation) and the g

相关标签:
11条回答
  • 2020-12-08 10:18
    1. Make a div element and place the chart canvas inside of it, name it as canvas-holder. See below:

       <div id="canvas-holder">
          <canvas id="myChart"></canvas>
       </div>
      
    2. Using CSS, specify the height and width of the canvas holder

       #canvas-holder {
          background-color: #FFFFFF;
          position: absolute;
          width: 400px;
          height: 400px;
       }
      
    0 讨论(0)
  • 2020-12-08 10:23

    The real issue is that the canvas will re-scale responsively to its parent. I wanted to keep the responsiveness. So something like this will solve the issue:

    <div style="width:50%">
        <canvas id="myChart"></canvas>
    </div>
    
    0 讨论(0)
  • 2020-12-08 10:24

    The width and height property that you set for the canvas only work if the Chartjs' responsive mode is false (which is true by default). Change your stats_tab.js to this and it will work.

        window.onload=function(){
            var ctx = document.getElementById("myChart").getContext("2d");
            var myChart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: [1,2,3,4,5,6,7,8,9,10],
                    datasets: [
                        {
                            label: "My First dataset",
                            data: [1,2,3,2,1,2,3,4,5,4]
                        }
                    ]
                },
                options: {
                    responsive: false
                }
            });
        }
    
    0 讨论(0)
  • 2020-12-08 10:24

    Below code from Chart.js documentation worked for me. "https://www.chartjs.org/docs/latest/general/responsive.html"

    var ctx = document.getElementById('myChart').getContext('2d');
    ctx.canvas.parentNode.style.width = "500px";
    ctx.canvas.parentNode.style.height = "500px";
    var myChart = new Chart(ctx, .....
    
    0 讨论(0)
  • 2020-12-08 10:27

    A little late to the party, but I struggled with this problem a lot, particularly on a page with multiple charts.

    This little tidbit solved it all - my charts all now fit nicely, and resize exactly with the divs they are in.

    Add this to your page styles (The 8px is personal preference. Change if needed):

    <style type="text/css">
        #canvas-holder {
            background-color: #FFFFFF;
            position: absolute;
            top: 8px;
            left: 8px;
            right: 8px;
            bottom: 8px;
        }
    </style>
    

    For the appropriate Divs:

    <div id="canvas-holder">
        <canvas id="chart-area"></canvas>
    </div>
    
    0 讨论(0)
提交回复
热议问题