首页 > 解决方案 > Chart.js:尽管没有错误,但模块未显示图表 - JS

问题描述

为了构造我的代码,我尝试实现模块。我想创建一个能够从 ChartJs 库创建图表的类。

基本上,我有三个文件

索引.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();

我没有错误。我试图创建一个封装工作代码的函数

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

  }

所以我的猜测是我的画布没有很好地实例化,但我不知道为什么。

你能帮我吗?

标签: javascriptchart.jschartjs-2.6.0

解决方案


尝试将您的自定义类重命名为不同的名称Chart。如果我记得最近其他人遇到了同样的问题并解决了它


推荐阅读