我知道有这样的问题,但我仍然找不到解决方法,我查看了控制台并看不到任何东西。有两个图像,一个应该出现在设定的坐标上,另一个是跟随鼠标的,一个不应该跟随鼠标的图像不会显示,但另一个会显示。
主.js
/**
* Created with JetBrains WebStorm.
* User: Script47
* Date: 22/09/13
* Time: 00:54
*/
function drawAvatars() {
// Create variable for the canvas & create a new object for image
var gameCanvas = document.getElementById("gameCanvas");
var userImage = new Image();
// The source of the images
userImage.src = ("Images/userImage.png");
// Create an event listener then call function redrawAvatar
gameCanvas.addEventListener("mousemove", redrawAvatar);
}
function redrawAvatar(mouseEvent) {
var gameCanvas = document.getElementById("gameCanvas");
var userImage = new Image();
var enemyImage = new Image();
var score = 0;
userImage.src = ("Images/userImage.png");
enemyImage.src = ("Images/enemyImage.png");
// Erase canvas sort of refresh, then re-draw image following the coordinates of the mouse in the canvas
gameCanvas.width = 400;
gameCanvas.getContext("2d").drawImage(userImage, mouseEvent.offsetX, mouseEvent.offsetY);
gameCanvas.getContext("2d").drawImage(enemyImage, 150, 150);
// Simple hit detection to see if user image hits enemy image
if (mouseEvent.offsetX > 130 && mouseEvent.offsetX < 175 && mouseEvent.offsetY > 130 && mouseEvent.offsetY < 175) {
score++;
alert("You hit the enemy!\n You score is: " +score);
}
}
索引.html
<!DOCTYPE html>
<html>
<head>
<title>Avoid Me | Game</title>
<link rel="stylesheet" type="text/css" href="CSS/styles.css">
<script src="JS/Main.js"></script>
</head>
<body>
<br/>
<center><h3>Avoid Me!</h3>
<br/>
<br/>
<canvas id="gameCanvas" height="300" width="400" onclick="drawAvatars();">
<p><strong>Notice:</strong> Browser does not support canvas!</p>
</canvas>
</center>
</body>
</html>