javascript 画布在javascript中为空错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17881624/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 09:58:39  来源:igfitidea点击:

Canvas is null error in javascript

javascripthtmlcanvas

提问by Sora

i have this code :

我有这个代码:

<!DOCTYPE html>
<html>
 <head>
 <style type="text/css">
 canvas{border:#666 1px solid;}
</style>
<script type="text/javascript">

var canvas = document.getElementById("canvas"),
        context = canvas.getContext("2d"),
        playerimage = new Image(),
        x = canvas.width / 2, //align to centre of the screen
        y = canvas.height / 2, //same as above
        speed = 5, //speed for the player to move at
        width = 50, //width of the player
        height = 50; //height of the player

  function init() {


   playerimage.src = "ninja.png"; //path to the image to use for the player
   canvas.addEventListener("keypress", update);
  }

  function update(event) {
    if (event.keyCode == 38) {
        y -= speed; //going up
    }
    if (event.keyCode == 40) {
        y += speed; //going down
    }
    if (event.keyCode == 37) {
        x -= speed; //going left
    }
    if (event.keyCode == 39) {
        x += speed; //going right
    }
    render();
}

function render() {
   // context.clearRect(0, 0, canvas.width, canvas.height);
    context.drawImage(playerimage, x, y, width, height);

}
   </script>
 </head>
    <body onload="init();">
   <button onclick="init();">Draw</button>
    <canvas id="Mycanvas" width="550" height="400"></canvas>
   </body>  
  </html>

the javascript console always give me canvas is null error

javascript 控制台总是给我画布为空错误

回答by nnnnnn

There are two problems with the following line of code:

下面这行代码有两个问题:

var canvas = document.getElementById("canvas"),
  1. It runs before the canvas element has been parsed and added to the DOM.
  2. It uses the wrong ID.
  1. 它在 canvas 元素被解析并添加到 DOM 之前运行。
  2. 它使用了错误的 ID。

Change it to:

将其更改为:

var canvas = document.getElementById("Mycanvas"),

...and move the whole <script>block to the end of the body, just before </body>.

...并将整个<script>块移动到正文的末尾,就在</body>.

回答by Madeyedexter

Your id of the canvas in html does not match the one you use in

您在 html 中画布的 ID 与您在其中使用的 ID 不匹配

var canvas=document.getElementById("canvas");

Correct HTML should be:

正确的 HTML 应该是:

<canvas id="canvas" width="550" height="400"></canvas>