Chartjs图表没有用帕格模板渲染

时间:2017-04-11 15:57:28

标签: node.js express pug chart.js

我正在尝试使用chartjs在哈巴狗模板中渲染图表但由于某种原因它不起作用,任何人都可以看到我做错了吗?哈巴狗文件加载得很好,但没有图表。这是我的哈巴狗模板:

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(
    -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'
                },
            }
        });
        );

1 个答案:

答案 0 :(得分:1)

您的代码有两个问题......

1。有语法错误!您需要在,对象

结束后放置data

2. 您需要将颜色值作为字符串传递(除非它们是预定义的变量)

另外,您应该将图表生成代码包装在窗口onload事件中,以确保在成功加载chart.js脚本之前不执行代码。

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'
                },
            }
        });
        };

另外,看看这个working chart demo on JSFiddle raw-js