2015-04-24 63 views
0

我想让我的图像跟随我的鼠标。我使用了大学的演讲指南来创建此代码,它看起来与我见过的所有代码相同,但我在Chrome开发人员工具中遇到了以下错误: 未捕获的TypeError:thisCanvas.addEventListener不是函数HTML5画布和JS - 鼠标移动,奇怪的错误

有什么建议吗?我已经盯着这几个小时了。

<!DOCTYPE html> 
<html> 
    <head> 
     <title> Gravity Game </title> 
     <meta charset = "UTF-8"> 
     <link type = "text/css" rel = "stylesheet" href = "style.css"> 
    </head> 

    <body onLoad="start_game()"> 
     <header> 
      <h1 id = "title1"> Gravity </h1> <h1 id = "title2"> Game </h1> 
     </header> 

     <ul id = "nav"> 
      <li class = "inactive"><a href = "about.html"> About </a></li> 
      <li id = "active"><a href = "play.html"> Play Game </a></li> 
     </ul> 

     <canvas id = "myCanvas" width = "1500" height = "500"></canvas> 

     <script> 
      var thisCanvas = document.getElementById("myCanvas").style.background = 'white'; 
      var context = myCanvas.getContext("2d"); 
      var worldX = 100; 
      var worldY = 100; 

      //Draw a circle 
      /*context.beginPath(); 
      context.arc(95, 50, 40, 0, 2 * Math.PI); 
      context.closePath(); 
      context.fill();*/ 

      thisCanvas.addEventListener("mousemove",seen_move,false); 

      function seen_move(e) 
      { 
       var bounding_box = thisCanvas.getBoundingClientRect(); 
       worldX = (e.clientX-bounding_box.left) * (thisCanvas.width/bounding_box.width); 
       worldY = (e.clientY-bounding_box.top) * (thisCanvas.height/bounding_box.height); 
      } 

      function start_game() 
      { 
       setInterval(loop_game, 50); 
      } 

      function loop_game() 
      { 
       thisCanvas.width = thisCanvas.width; 
       update_world(worldX, worldY); 
      } 

      function update_world(x, y) 
      { 
       var world_img = new Image(); 
       world_img.src = "images/world.png"; 
       context.drawImage(world_img, x, y); 
      } 



     </script> 

    </body> 

</html> 

回答

3
var thisCanvas = document.getElementById("myCanvas").style.background = 'white'; 

thisCanvas现在拥有的字符串值white

thisCanvas.addEventListener()基本上就像是在说'white'.addEventListener()。因为没有String.prototype.addEventListener,这是行不通的。

您需要将document.getElementById("myCanvas")分配到thisCanvas然后设置其背景颜色。

1
var thisCanvas = document.getElementById("myCanvas").style.background = 'white'; 

应该

var thisCanvas = document.getElementById("myCanvas") 

您试图分配你的画布风格变化的方法为变量thisCanvas,而不是分配的canvas元素本身

+0

谢谢,这工作。我已将背景样式添加到css页面。 –

1

的问题是:

var thisCanvas = document.getElementById("myCanvas").style.background = 'white'; 

thisCanvas不包含对canvas>元素的引用。相反,由于链接分配,它必然会受到'white'的限制。

你可能想是这样的:

var thisCanvas = document.getElementById("myCanvas"); 
thisCanvas.style.background = 'white';