Search code examples
htmljqueryamcharts

Draw a plot on top of a canvas using jquery


really would appreciate any help on the below. My knowledge of jquery/html is very limited. I'm trying to figure out this issue from a project that was started by someone else.

Essentially I have created a "canvas" tag within HTML, with aim of adding a line chart on it upon clicking another HTML component.

Below is my HTML code

                <body>
                    <div id = "myModal" class="modal">
                        <div class="modalContent">
                            <span class = "close"> &times; </span>
                            <canvas id="data_chart"></canvas>
                        </div>
                    </div>
                </body>

Here's my jquery code

            $(document).on('click', "#country_data_detail_table tbody tr", function(e){
                $("*[id='myModal']").css('display', 'block');
                renderChart();
            });

function renderChart() {

                  var ctx = $('canvas[id="data_chart"]')[0].getContext('2d');
                  //===========================
                  var len = data_obj["trend"]["x"].length;
                  var trend_data = []

                  for (var i=0; i<len; i++){
                      var d = new Date(data_obj["trend"]["x"][i]);
                      var t = {"date": d, "value": data_obj["trend"]["y"][i]};
                      trend_data.push(t)};


                  var chart = am4core.create(ctx, am4charts.XYChart);
                  chart.data=trend_data;
                  var dateAxis_line = chart.xAxes.push(new am4charts.DateAxis());

                  // Create value axis
                  var valueAxis = chart.yAxes.push(new am4charts.ValueAxis());
                  var series = chart.series.push(new am4charts.LineSeries());
}

However, while the canvas object appears (I can confirm as I add a border around it which appears), the chart is not rendered.

I have searched extensively on stackoverflow and found this question which is very similar to mine, but I can't seem to adapt it successfully. Chart.js modal window

Many thanks for any help given.


Solution

  • AmCharts uses SVG so you can't put it inside a canvas element. Change it to a div, e.g. <div id="data_chart"></div> and remove your canvas-related code.

    var chart = am4core.create("data_chart", am4charts.XYChart);
    

    This assumes that the rest of your chart code is set up correctly (your dataFields are assigned to your series in the rest of your renderChart function).