我有这个工作的javascript / HTML代码,它绘制了CanvasJS的基本折线图,用于一些基本的测试数据。见下文。我不想使用谷歌图表,因为我已经尝试过它和谷歌图表有内存泄漏,这使谷歌图表或多或少对我无用。
<!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>
我知道如何从名为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>
但由于绘图代码的复杂性,我无法模仿这样的工作代码。
您可以将数据从HTML传递到外部JS文件中定义的函数并渲染图表。这是工作代码:https://1drv.ms/u/s!Am6ZJqYg9Zmfgyj5JROGJigcwArr