【问题标题】:error: Uncaught TypeError: Cannot read property 'getContext' of null错误:未捕获的类型错误:无法读取 null 的属性“getContext”
【发布时间】:2020-07-25 09:04:25
【问题描述】:

当我写的时候:

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>

我得到一个错误:

错误:未捕获的类型错误:无法读取 null 的属性“getContext”

我检查了我的代码 5 次, 试图找到该怎么做, 并查看帖子。 请帮我。 我想制作一个游戏和我的朋友一起玩(:

你可以帮我找到如何制作地图。 如果你想为游戏提供帮助,请告诉我(:

【问题讨论】:

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

标签: javascript


【解决方案1】:

你指错了id

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

应该是:

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

【讨论】:

    猜你喜欢
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-18
    • 2015-08-19
    • 2012-02-18
    • 2015-02-13
    相关资源
    最近更新 更多