从外部 .JS 文件中使用 HTML 中的 CanvasJS 绘图

Plotting with CanvasJS in HTML from an external .JS file

我有这个有效的 javascript / HTML 代码,它使用 CanvasJS 为一些基本测试数据绘制基本折线图。见下文。我不想使用 google 图表,因为我已经尝试过并且 google 图表有内存泄漏,这使得 google 图表对我来说或多或少没有用。

<!DOCTYPE HTML>
<html>
<head>  
<script>
window.onload = function () {

var chart = new CanvasJS.Chart("chartContainer", 
{
animationEnabled: false,
backgroundColor: "#000000", 
title:{ text: "Price chart for crypto currency: ", fontSize: 22, fontFamily: "arial", fontWeight: "lighter", 
fontColor: "white", horizontalAlign: "left"},
axisY:{ includeZero: false, tickColor: "white", lineColor: "white", 
labelFontColor: "white", gridColor: "white", gridThickness: 0.5},
axisX:{ minimum: 1, maximum: 5.1, interval: 1, tickColor: "white", 
lineColor: "white", labelFontColor: "white", gridColor: "white", gridThickness: 0.5}, 
data: [{type: "line", dataPoints: 
[
{ x: 1, y: 450 },
{ x: 2, y: 414},
{ x: 3, y: 520},
{ x: 4, y: 460 },
{ x: 5, y: 450 }
]
}]

});

chart.render();

}
</script>
</head>
<body>
<div id="chartContainer" style="width: 80%; height: 450px;"></div>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
</body>
</html>

现在,我想提取基本的绘图代码函数并将其放入名为 plot.js 的外部 .js 文件中名为 PlotData() 的 javascript 函数中,该文件位于同一文件夹中作为 HTML 文件。最后的想法是从 HTML 调用这样的函数,并将数据作为函数参数,如 PlotData([{x:1, y:450}, {x:2, y:414} 等等等等 ])。这将使 HTML 代码更简单、更通用,这意味着我也可以将它用于其他数据。

我在下面尝试过这样做。我还没有将数据放入函数参数中,因为代码不起作用。我必须一次解决一个问题。首先,让外部 .js 绘图代码正常工作,然后将数据添加为绘图函数参数。

function PlotData() 
{
var chart = new CanvasJS.Chart("chartContainer", 
{
animationEnabled: false,
backgroundColor: "#000000", 
title:{ text: "Price chart for crypto currency: ", fontSize: 22, fontFamily: "arial", fontWeight: "lighter", 
fontColor: "white", horizontalAlign: "left"},
axisY:{ includeZero: false, tickColor: "white", lineColor: "white", 
labelFontColor: "white", gridColor: "white", gridThickness: 0.5},
axisX:{ minimum: 1, maximum: 5.1, interval: 1, tickColor: "white", 
lineColor: "white", labelFontColor: "white", gridColor: "white", gridThickness: 0.5}, 
data: [{type: "line", dataPoints: 
[
{ x: 1, y: 450 },
{ x: 2, y: 414},
{ x: 3, y: 520},
{ x: 4, y: 460 },
{ x: 5, y: 450 }
]
}]

});

chart.render();

}
<!DOCTYPE HTML>
<html>
<head>  
<script type="text/javascript" src='plot.js'> </script> 
<script>
window.onload = PlotData();  
</script>
</head>

<body>
<div id="chartContainer" style="width: 80%; height: 450px;"></div>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
</body>
</html>

我知道如何从位于与 HTML 代码相同的文件夹中的名为 test3 的外部 .js 文件成功地将数据添加到函数参数 xxx(a)。

function xxx(a)
{ 
alert("Value of a = " + a);  
}
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src='test3.js'> </script>
</head>

<body>

<script>

xxx([1,2,3,4,5]); 

</script>

</body>
</html>

但是由于绘图代码的复杂性,我无法模拟这样的工作代码。

您可以将数据从 HTML 传递到外部 JS 文件中定义的函数并呈现图表。这是工作代码:https://1drv.ms/u/s!Am6ZJqYg9Zmfgyj5JROGJigcwArr