Search code examples
meteorcanvasjs

CanvasJS conversion not working in MeteorJS


I am trying to convert a basic CanvasJS script to meteor format so that I can add a reactive chart to an app that is being built on on real time data. However, when I convert the code it is coming up blank when rendered. At this point, I removed the "timer" code that would dynamically update the page just to get a static view to work. If you have tips on how to use the template.rendered to create the timing aspect that would be great (tried and failed too).

HTML and JS below...thanks in advance

Original code @ http://canvasjs.com/docs/charts/how-to/creating-dynamic-charts/

index.html:

<head>
    <script src="http://canvasjs.com/assets/script/canvasjs.min.js"></script>       
</head>
<body>
    {{> canvaschart}}
</body>

<template name="canvaschart">
    <div class="chartContainer" style="height: 300px; width: 600px;"></div>
</template>

index.js code:

if (Meteor.isClient) {

    Meteor.startup(
        function() {
            new CanvasJS.Chart('.chartContainer', chartconfig);
    });

    //var dps for dyno chart
    var dps = [{x: 1, y: 10}, {x: 2, y: 10}, {x: 3, y: 10}, {x: 4, y: 10}, {x: 5, y: 10}];   //dataPoints.

    var chartconfig =
        {
            title :{
                text: "Live Data"
            },
            axisX: {                        
                title: "Axis X Title"
            },
            axisY: {                        
                title: "Units"
            },
            data: [{
                type: "line",
                dataPoints : dps
            }]
        };   
};

Solution

  • You run the code in Meteor.startup. That method executes before any template is rendered, so your container div is not yet in the DOM. You need to execute the code in your template's onRendered method. In other words, replace

    Meteor.startup(function() {...});
    

    with

    Template.canvaschart.onCreated(function() {...});