Chartjs-Chartjs chart not rendering with pug template

1👍

You have two issues with your code …

1 . There’s a syntax error! You need to put , after the end of data object

2 . You need to pass the color values as a string (unless they are predefined variables)

also, you should probably wrap the chart generating code inside a window onload event to make sure the code doesn’t get executed before the chart.js script is loaded successfully.

div(class="main container-fluid text-center")
    div(class="choices")
        h2
        p I'm voting for:
        select(class="form-control")
            option 1
            option 2
            option 3
            option 4
            option 5
    div(class="chart")        
    canvas(id="chartPic" width="400" height="400")
script(src="chart.js")
script. 
    -window.onload = function() {
    -var red="#{red}", green="#{green}", blue="#{blue}";
    -var ctx = document.getElementById("chartPic").getContext('2d');
       -var chart = new Chart(ctx,  {
            -type: 'pie',
            -data: {
                -labels: ["red", "green", "blue"],
                -datasets: [{
                    -label: 'Number of votes',
                    -data: [1, 1, 1],
                    -backgroundColor: [red, green, blue],
                    -borderColor: [green, blue, red],
                    -borderWidth: 1
                }],
                },
            -options: {
                -title: { 
                    -display: true,
                    -text: "chart",
                },
                -legend: {
                    -position: 'bottom'
                },
            }
        });
        };

also, have a look at this working chart demo on JSFiddle raw-js

Leave a comment