javascript - 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: {},
});
}
所以我的猜测是我的画布没有很好地实例化,但我不知道为什么。
你能帮我吗?
解决方案
尝试将您的自定义类重命名为不同的名称Chart
。如果我记得最近其他人遇到了同样的问题并解决了它
推荐阅读
- javascript - 根据 Gatsby 中的 url 更改字体颜色
- visual-studio-code - 如何在 VS Code 中更改终端的语言
- spring - 无法将 thymeleaf springsecurity 或布局方言添加到我的应用程序
- c# - 使用 Gremlin.net 读取/保存文件
- c# - 仅更新给定值(实体框架)
- node.js - 如何修复无法获取快递中的错误?
- django - Wagtail,在使用 AppPageMixin 时添加更多字段
- r - 将水平值转换为垂直列,在R中一个接一个地粘贴
- plot - 如何解决 R 中 ggraph 中的“仅支持连接图”问题?
- html - 如果我添加更多文本,空白弹出窗口会增加吗?看图片