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

时间:2019-03-13 23:02:28

标签: javascript html canvasjs

我有这个可运行的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>

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

我尝试在下面执行此操作。我尚未将数据放入function参数,因为代码无法正常工作。我必须一次解决一个问题。首先,使外部.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>

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

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>

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

1 个答案:

答案 0 :(得分:0)

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