Javascript 尝试获取画布时出现未捕获类型错误
我正在尝试学习使用Chartjs,当我试图通过其ID获取canvas元素时遇到了一个问题。由于某些原因,它没有被定义。这是因为我正在调用Javascript 尝试获取画布时出现未捕获类型错误,javascript,html,canvas,chart.js,Javascript,Html,Canvas,Chart.js,我正在尝试学习使用Chartjs,当我试图通过其ID获取canvas元素时遇到了一个问题。由于某些原因,它没有被定义。这是因为我正在调用document.getElementByID,而这不是在HTML文件中运行的吗?我试图使用一个外部文件来承载我所有的JS,而不是凌乱我的HTML文件 错误消息: 未捕获类型错误:未定义不是函数 在charts-option.js的第2行找到:var ctx=document.getElementByID(“会话图”).getContext(“2d”) inde
document.getElementByID
,而这不是在HTML文件中运行的吗?我试图使用一个外部文件来承载我所有的JS,而不是凌乱我的HTML文件
错误消息:
未捕获类型错误:未定义不是函数
在charts-option.js的第2行找到:var ctx=document.getElementByID(“会话图”).getContext(“2d”)代码>
index.html
<!doctype html>
<html>
<head>
<title>Google Super Proxy Test</title>
<script src="Chart.min.js"></script>
<script src="chart-options.js"></script>
</head>
<body>
<div style="width: 50%">
<canvas id="sessions-graph" height="450" width="600"></canvas>
</div>
</body>
</html>
您的代码有输入错误,方法应该是document.getElementById()
计时如何?引用时是否存在#sessions graph
?@Lee很受欢迎,但现在它显示了未捕获的类型错误:无法读取null的属性“getContext”
。似乎找不到canvas元素。有什么想法吗?@Teemu问得好。可能是我的JS在调用画布之前运行。将脚本移动到结束正文标记之前,应该修复该问题。是的。谢谢你,李和蒂姆。通过将所有内容包装在window.onload=function(){…}
中,除了输入错误之外,您还试图引用body
中尚不存在的元素。在窗口中包装脚本。在#会话图
之后,加载
或将
标记移动到正文
。
// Get the context of the canvas element
var ctx = document.getElementByID("sessions-graph").getContext("2d");
var sessionsGraph = new Chart(ctx).Bar(data); //Create a chart with "data" array
var data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "My First dataset",
fillColor: "rgba(220,220,220,0.5)",
strokeColor: "rgba(220,220,220,0.8)",
highlightFill: "rgba(220,220,220,0.75)",
highlightStroke: "rgba(220,220,220,1)",
data: [65, 59, 80, 81, 56, 55, 40]
},
{
label: "My Second dataset",
fillColor: "rgba(151,187,205,0.5)",
strokeColor: "rgba(151,187,205,0.8)",
highlightFill: "rgba(151,187,205,0.75)",
highlightStroke: "rgba(151,187,205,1)",
data: [28, 48, 40, 19, 86, 27, 90]
}
]
};
Chart.defaults.global = {
//Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
scaleBeginAtZero : true,
//Boolean - Whether grid lines are shown across the chart
scaleShowGridLines : true,
//String - Colour of the grid lines
scaleGridLineColor : "rgba(0,0,0,.05)",
//Number - Width of the grid lines
scaleGridLineWidth : 1,
//Boolean - If there is a stroke on each bar
barShowStroke : true,
//Number - Pixel width of the bar stroke
barStrokeWidth : 2,
//Number - Spacing between each of the X value sets
barValueSpacing : 5,
//Number - Spacing between data sets within X values
barDatasetSpacing : 1
}