图像不会在画布上加载。 canvas.width错误

时间:2014-02-13 11:44:58

标签: javascript html canvas

嘿,我的形象不会加载到画布上。我已经在这几个小时了,我无法弄清楚它是什么。我开始在谷歌浏览器中调试我的代码,控制台说canvas.width设置为null。这是我能找到的唯一错误。

这是我的代码:

function gameLoop()
 {

     drawBackground();
     drawPlayer();
 }
 function drawBackground()
 {
   var img = new Image();   
img.src = "Images/GrassTexture.png";
   g.drawImage(img,0, 0, 500, 500); 
 }
 function drawPlayer()
 {
  var player1 = new Image();   
player1.src = "Images/Players/Mignolet.png";
   g.drawImage(player1,0, 0,50 , 50); 
 }
  setInterval(gameLoop, 1);
   var canvas = document.getElementById("Canvas");
    canvas.width = 500;
    canvas.height = 500;
   var g = canvas.getContext("2d");

HTML

html>
    <head>
        <title>Football</title>
        <link rel="stylesheet" type="text/css" href="Css/Css.css">
    </head>
    <body>
        <script type="text/javascript" src="Js/Js.js"></script>
        <div id="Background">
            <div id="Header">
            </div>
        <div id="Wrapper">
       <canvas id="Canvas">
       </canvas>  
        </div>
        </div>
    </body>
</html>

的CSS

#Canvas
{
    border: 1px solid black;
    width:500px;
    height:500px;
    margin-left: 300px
}

1 个答案:

答案 0 :(得分:0)

在呈现html之前调用脚本,这就是您收到错误的原因。最好在<body>标记结束之前放置脚本。

<html>
<head>
    <title>Football</title>
    <link rel="stylesheet" type="text/css" href="Css/Css.css">
</head>
<body>       
    <div id="Background">
        <div id="Header">
        </div>
    <div id="Wrapper">
   <canvas id="Canvas">
   </canvas>  
    </div>
    </div>
     <script type="text/javascript" src="Js/Js.js"></script>
</body>