我想让我的图像跟随我的鼠标。我使用了大学的演讲指南来创建此代码,它看起来与我见过的所有代码相同,但我在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>
谢谢,这工作。我已将背景样式添加到css页面。 –