Reputation: 3
I'm using regular JS (I know it isn't the best, but I'm a beginner)
So I'm writing code for a canvas project. However when using the getContext() function the JS console says
Uncaught TypeError: canvas.getContext is not a function at master.js:4
I've looked around and found that nothing has fixed my problem.
var canvas = document.getElementsByClassName('myCanvas');
console.log(canvas);
var context = canvas.getContext('2d');
console.log(context);
The HTML is this:
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="master.js" charset="utf-8"></script>
<link rel="stylesheet" href="master.css">
</head>
<body>
<canvas class="myCanvas">Your browser doesn't support HTML canvas</canvas>
</body>
</html>
Does anyone know what I am doing wrong?
Upvotes: 0
Views: 4033
Reputation: 1197
getElementsByClassName
returns an array of elements. Thus, it does not have the method you are looking for. Try the following:
var canvas = document.getElementsByClassName('myCanvas')[0];
console.log(canvas);
var context = canvas.getContext('2d');
console.log(context);
Your code is also stored in the HTML head, so your canvas element will not be found. Either put your <script>
tag in the HTML <body>
tag or set a function inside document.onload
as follows:
document.onload = function() {
var canvas = document.getElementsByClassName('myCanvas')[0];
console.log(canvas);
var context = canvas.getContext('2d');
console.log(context);
}
Upvotes: 3