我在我的节点应用chartJS 2.7.1
中使用。
我的pug文件如下所示:
extends layouts/_layout.pug
block content
.page-title
div
h1
i.fa.fa-dashboard
| Bitcoin Price Example
.row
.col-md-12
.card
h3.card-title Loading local bitcoin file
canvas#canvas.chartjs-render-monitor(style='display: block; width: 1000px; height: 500px;', width='1000', height='500')
console.log(data)
block specific-js
script(type='text/javascript', src="js/chartJS_price.js")
script(type='text/javascript', src="js/plugins/chart.js") // The Chart JS library
chartJS_price.js
文件如下所示:
const lineChartData = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: "Price",
borderColor: 'rgba(255,99,132,1)',
backgroundColor: 'rgba(255, 99, 132, 0.2)',
fill: false,
data: [
5,
6
],
yAxisID: "y-axis-1",
}, {
label: "MarketCap",
borderColor: 'rgba(54, 162, 235, 0.2)',
backgroundColor: 'rgba(54, 162, 235, 1)',
fill: false,
data: [
1,
3
],
yAxisID: "y-axis-2"
}]
};
window.onload = function () {
var ctx = document.getElementById("canvas").getContext("2d");
window.myLine = Chart.Line(ctx, {
data: lineChartData,
options: {
responsive: true,
hoverMode: 'index',
stacked: false,
title: {
display: true,
text: 'Bitcoin Price and MarketCap'
},
scales: {
yAxes: [{
type: "linear", // only linear but allow scale type registration. This allows extensions to exist solely for log scale for instance
display: true,
position: "left",
id: "y-axis-1",
}, {
type: "linear", // only linear but allow scale type registration. This allows extensions to exist solely for log scale for instance
display: true,
position: "right",
id: "y-axis-2",
// grid line settings
gridLines: {
drawOnChartArea: false, // only want the grid lines for one axis to show up
},
}],
}
}
});
};
我的app.js
文件中的路由如下所示:
// routes
app.get('/price', (req, res) => {
const priceData = JSON.parse(fs.readFileSync(path.join(__dirname, './data/prices.json'), 'utf8'))
res.render('prices', {
priceData,
})
})
如您所见,我正在加载price
中的route
数据,并将其传递给view
。我正在使用我的自定义pug
规范在我的chartjs
文件中加载脚本。
有关如何将我的priceData
变量从我的路径注入加载的chartJS_price.js
的pug模板中的任何建议。
有任何建议怎么做?
答案 0 :(得分:1)
pug文件没问题,您只需对chart_price.js
文件进行一些更改,通过ajax向服务器发出请求,并在服务器文件中,而不是渲染文件,读取文件内容并使用
res.send(//your json data)
。