Chartjs-My canvas/graph jumps to left after creating the object

0👍

I found your problem…!

On initial time the canvas is set to display: block you need to change into this display: inline-block; after ; semi-colon on canvas tag under style

You can add align="center" or class="text-center" on canvas tag as you wish

Eg:

<canvas id="myCanvas" align="center" width="100" height="100" style="border:1px solid #000000; display: inline-block;">

This is Solution you can check here

$(document).ready(function() {
  $('#my_graph').append('<canvas id="myCanvas" align="center" width="100" height="100" style="border:1px solid #000000; display: inline-block;">');
});

$('#test_button').click(function(event) {
  drawGraph();
})


function drawGraph() {
  var ctx = document.getElementById('myCanvas');
    
  myLineGraph = new Chart(ctx, {
    type: 'line',
    data: {
      labels: [0],
      datasets: [{
        data: [0],
        label: "nr1",
      }]
    },
    options: {
      responsive: false
    }
  });
}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>Test</title>
    <!-- Latest compiled and minified Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
</head>

<body>
    <div class="container-fluid">
        <div class="col-sm-12">
            <div id="my_graph" class="text-center" >Graph: <br></div>
            <button id="test_button" type="button" class="btn btn-primary">test_button</button>
        </div>
    </div>

    <!-- jQuery library -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <!-- Popper JS -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
    <!-- Latest compiled JavaScript -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
    <!-- Bootstrap validator -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/1000hz-bootstrap-validator/0.11.9/validator.min.js"></script>
    <!-- chart.js -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
    <!-- Import custom JavaScript -->
    <script src="./js.js"></script>
</body>

</html>

Leave a comment