Reputation: 9536
I get this error: "cannot read property 'getContext' of null" I looked up others with this issue, all of them had their JS running before their HTML div was created, but that is not the case for me. I have linked a JSFiddle with my code, but it doesn't work well because I have fixed elements. Someone please help, I have no idea what is going on. JSFIDDLE: https://jsfiddle.net/alec935/Ln7yghbx/1/
HTML:
<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<head>
<title>Snake</title>
<link rel="stylesheet" href="snake.css">
<script type="text/javascript" src="jquery-3.2.0.min.js"></script>
</head>
<body>
<div id="game">
<div id="play">
<canvas id="playBoard"></canvas>
<script src="snake.js"></script>
</div>
<div id="credits"><h1><i>Snake Game</i>, designed by Alec xxxxx</h1></div>
<div id="info"></div>
</div>
</body>
</html>
CSS:
@keyframes pulsate {
0% {color:white}
50% {color:black;}
100% {color:white}
}
body {
background-image:url(images/snaxe.jpg);
background: fill;
}
#game{
width:1450px;
height:800px;
background-color:black;
margin: 0 auto;
position:relative;
}
#credits {
color: white;
font-size: 19px;
text-shadow: rgb(255, 255, 255) 0px -1px 4px, rgb(255, 255, 0) 0px -2px 10px, rgb(255, 128, 0) 0px -10px 20px, rgb(255, 0, 0) 0px -18px 40px;
animation: pulsate 4s infinite;
}
#play{
width:720px;
height:720px;
background-color:red;
z-index:1;
}
#playBoard {
width:720px;
height:720px;
z-index:0;
}
#info{
position:fixed;
top:8px;
right:115px;
width:730px;
height:800px;
background-color:white;
z-index: 1;
}
JavaScript:
$(function() {
var snakeX, snakeY;
var fruitX, fruitY;
var gameOver = true;
var direction = 0; //0 = null, 1 = left, 2 = right, 3 = up, 4 = down
function Draw() {
var canvas = document.getElementById("playBoard");
var ctx = canvas.getContext("2d");
//Snake
ctx.beginPath();
ctx.lineWidth="5";
ctx.strokeStyle="green";
ctx.fillRect(385,385,50,50);
}
function Setup() {
gameOver = false;
Draw();
}
window.onload = Setup;
});
Edit: I had a typo in my canvas element. This has since been fixed. The problem still persists, however.
Upvotes: 0
Views: 649
Reputation: 51
You're trying to select the element with the id playBoard, but you haven't assigned it to your canvas, probably just a typo.
<canvas>id="playBoard"</canvas>
should be <canvas id="playBoard"></canvas>
Upvotes: 0
Reputation: 1612
You have a typo on the canvas element. Change this:
<canvas>id="playBoard"</canvas>
to this:
<canvas id="playBoard"></canvas>
In other words, put the id on the element itself
Upvotes: 0
Reputation: 6195
Double check your HTML. Your id is misplaced.
<canvas>id="playBoard"</canvas>
should be
<canvas id="playBoard"></canvas>
Upvotes: 1