首页 > 解决方案 > 无法读取 null 的属性“getContext”(没有 jQuery)

问题描述

我正在尝试用画布制作游戏,但我遇到了问题。我的问题是const ctx = canvas.getContext("2d");

我有错误Cannot read property 'getContext' of null

我查看了其他帖子对我的问题没有任何帮助(我不使用 jquery)

提前感谢您未来的回答<3

这是我的 HTML 代码和 JS 代码:

<html lang="fr">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
    
  <title>Human Run</title>

  <link href="./style.css" rel="stylesheet">
</head>

<body>

<header>
  <h1>Human Run</h1>
  <div class="score-container">
    <div id="bestScore"></div>
    <div class="currentScore"></div>
  </div>
</header>
<canvas class="landscape" id="fond" width="350" height="416"></canvas>
<canvas class="ground" id="sol" width="350" height="150"></canvas>

  <script src="./script.js" type="text/javascript" ></script>
  <script src="./ground.js" type="text/javascript" ></script>
</body>
</html>


JS CODE :

const canvas = document.getElementById('sol');
const ctx = canvas.getContext("2d");
const img = new Image();
img.src = '.media/ground2.png';


// réglages général
const speed = 6.2;

const render = () => {
  index++;
  
  // background
  ctx.drawImage(img, 0, 0, canvas.width, canvas.height, -((index * (speed / 2)) % canvas.width) + canvas.width, 0, canvas.width, canvas.height);
  
  ctx.drawImage(img, 0, 0, canvas.width, canvas.height, -((index * (speed / 2)) % canvas.width), 0, canvas.width, canvas.height);
  
  window.requestAnimationFrame(render);
}
img.onload = render;

标签: javascripthtmlcsscanvas

解决方案


您的问题似乎只是您的 javascript 在您的 html 之前加载,因此,您的 javascript 尝试使用当时不存在的元素(“sol”),因为它还不存在。两种解决方案要么将 async 放在您的 javascript<script>标记上

https://www.w3schools.com/tags/att_script_async.asp

或者用 document.addEventListener("DOMContentLoaded",()=>{/* 你的代码放在这里*/});

https://developer.mozilla.org/en-US/docs/Web/API/Document/DOMContentLoaded_event

document.addEventListener("DOMContentLoaded",()=>{
const ctx = sol.getContext("2d");
const img = new Image();
let index = 0;
img.src = 'http://fc04.deviantart.net/fs70/i/2012/014/c/9/rpg_floor_tiles_02_by_neyjour-d4me7dx.jpg';


// réglages général
const speed = 6.2;

const render = () => {
  index++;
  
  // background
  ctx.drawImage(img, 0, 0, sol.width, sol.height, -((index * (speed / 2)) % sol.width) + sol.width, 0, sol.width, sol.height);
  
  ctx.drawImage(img, 0, 0, sol.width, sol.height, -((index * (speed / 2)) % sol.width), 0, sol.width, sol.height);
  
  window.requestAnimationFrame(render);
}
img.onload = render;
});
<header>
  <h1>Human Run</h1>
  <div class="score-container">
    <div id="bestScore"></div>
    <div class="currentScore"></div>
  </div>
</header>
<canvas class="landscape" id="fond" width="350" height="416"></canvas>
<canvas class="ground" id="sol" width="350" height="150"></canvas>


推荐阅读