Bootstrap Modal with Chart.js linechart

2019-07-03 23:15发布

问题:

I have a Twitter Bootstrap 3 Modal window and i want to draw an Chart.js linechart in it. But every time i open the modal the canvas element has a height and a width of 0. If i change these values the chart is empty. it seems like the chart is never drawn but i doesnt get any console output or errors.

Modal:

<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                <h4 class="modal-title" id="exampleModalLabel">New message</h4>
            </div>
            <div class="modal-body">
                <p>Text</p>
                <canvas id="canvas" width="400" height="400"></canvas>
                <p>Text</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

Javascript:

$('#exampleModal').on('show.bs.modal', function (event) {

    var button = $(event.relatedTarget);
    var modal = $(this);
    var canvas = modal.find('.modal-body canvas');

    // Chart initialisieren
    var ctx = canvas[0].getContext("2d");
    var chart = new Chart(ctx).Line({
        labels: ["January", "February", "March", "April", "May", "June", "July"],
        datasets: [
            {
                fillColor: "rgba(190,144,212,0.2)",
                strokeColor: "rgba(190,144,212,1)",
                pointColor: "rgba(190,144,212,1)",
                pointStrokeColor: "#fff",
                pointHighlightFill: "#fff",
                pointHighlightStroke: "rgba(220,220,220,1)",
                data: [65, 59, 80, 81, 56, 55, 40]
            },
            {
                fillColor: "rgba(151,187,205,0.2)",
                strokeColor: "rgba(151,187,205,1)",
                pointColor: "rgba(151,187,205,1)",
                pointStrokeColor: "#fff",
                pointHighlightFill: "#fff",
                pointHighlightStroke: "rgba(151,187,205,1)",
                data: [65, 59, 80, 81, 56, 55, 40]
            }
        ]
    }, {});
});

Button:

<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" data-id="<?php echo $var["id"]; ?>">Open</button>

What is missing? Why the chart never gets drawn?

Thanks

回答1:

It was the wrong event.

$('#exampleModal').on('shown.bs.modal', function (event) {});

Works!