hungryboat1815
hungryboat1815

Reputation: 51

error: Uncaught TypeError: Cannot read property 'getContext' of null

when i write:

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
//var canvas = document.getElementById("canvas")
//var ctx = canvas.getContext("2d")
//var c = document.getElementById("canvas")
//var ctx = c.getCont#indevtext {
//ext("")

$("#start").click(function(){
  start()
})

function start() {
  $(document).ready(function(){
  $("#start").click(function(){
   $("canvas").show()
   $("#start").hide()
  })
})
}
sg()
start()

function sg() {
//ctx.clearRect(0, 0, canvas.width, canvas.height)
//ctx.BeginPath()
//ctx.arc(x, y, radius, 0, Math.PI*2);
//ctx.fillStyle = "brown";
//ctx.fill()
}

function frame() {
//ctx.clearRect(0, 0, canvas.width, canvas.height)
}

window.onload = function() {
//canvas = document.getElementById("canvas")
canvas.getContext("2d")
}
#indevtext {
  color: darkgreen;
  text-align: center;
  padding: 250px 0;
}

.container { 
  height: 200px;
  text-align: center;
  margin: 250px 0;
  position: relative;
  border: 3px solid green; 
}

.sd {
  margin: 0;
  position: absolute;
  top: 50%;
  left: 50%;
  -ms-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
}

#start {
  text-align: center;
  margin: 250px 0;
  color: limegreen;
}

#game {
border: black 1px solid;
background-color: #178735;
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<head>
  <body>
    <div>
      <div>
      <div>
       <canvas id="game" width="550px" height="587px"></canvas>
      <h1 id="start">Enter Game</h1>
      </div>
      </div>
    </div>
  </body>
</head>

i get a error:

error: Uncaught TypeError: Cannot read property 'getContext' of null

i check my code 5times, tried to find what to do, and check posts. please, help me. im want to make a game to play with my friends (:

and you can help me to find how to make a map. if you want to help for the game tell me (:

Upvotes: 0

Views: 1646

Answers (1)

Alberto
Alberto

Reputation: 12939

you are referring to the wrong id:

<canvas id="game" width="550px" height="587px"></canvas>
...         ^^^^
var canvas = document.getElementById('canvas');
                                     ^^^^^^^^

it should be:

var canvas = document.getElementById('game');

Upvotes: 1

Related Questions