Chart.js: chart not displayed from modules despite no errors – JS

In order to structure my code, I try to implement module.
I would like to create a class that would be able to create charts from ChartJs library.

Basically, I have three files

Index.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>


</head>

<body>

    <div>
        <canvas id="test"></canvas>
    </div>


</body>

<script type="module" src="index.js"></script>


</html>

chartjs.js

"use strict";

export default class Chart {
  constructor(ctx, type) {
    this.type = type;
    this.ctx = ctx;
  }

  setOptions(options) {
    this.options = options;
  }


  setData(data) {
    this.data = data;
  }


  drawChart() {
    var chart = new Chart(this.ctx, {
      // The type of chart we want to create
      type: this.type,
      // The data for our dataset
      data: this.data,
      // Configuration options go here
      options: this.options,
    });

    return {
      chart: chart,
    };
  }
}

index.js

import Chart from "/chart.js";

var data = {
  labels: ["January", "February", "March", "April", "May", "June", "July"],
  datasets: [
    {
      label: "My First dataset",
      backgroundColor: "rgb(255, 99, 132)",
      borderColor: "rgb(255, 99, 132)",
      data: [0, 10, 5, 2, 20, 30, 45],
    },
  ],
};
var ctx = document.getElementById("test").getContext("2d");
var chartObj = new Chart(ctx, "line");
chartObj.setData(data);
chartObj.setOptions({});
var chart = chartObj.drawChart();

I have no errors.
I tried to create a function that will encapsulate the working code

  test(ctx) {
    console.log("🚀 ~ file: index.html ~ line 28 ~ ctx", ctx);
    var chart = new Chart(ctx, {
      // The type of chart we want to create
      type: "line",

      // The data for our dataset
      data: {
        labels: [
          "January",
          "February",
          "March",
          "April",
          "May",
          "June",
          "July",
        ],
        datasets: [
          {
            label: "My First dataset",
            backgroundColor: "rgb(255, 99, 132)",
            borderColor: "rgb(255, 99, 132)",
            data: [0, 10, 5, 2, 20, 30, 45],
          },
        ],
      },

      // Configuration options go here
      options: {},
    });

  }

So my guess would be the fact that my canvas is not well instantiated but I don’t know why.

Could you please help me on that ?

13 thoughts on “Chart.js: chart not displayed from modules despite no errors – JS”

  1. Try renaming your custom class to something different then Chart. If I remember corrently someone else got the same issue and that fixed it

    Reply

Leave a Comment