我知道有这样的问题,但我仍然无法找到修复,我已经通过控制台查看,看不到任何东西。有两个图像,一个应该出现在设定的坐标上,另一个出现在鼠标之后,一个不是跟随鼠标的图像不显示,而另一个则显示。
Main.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);
}
}
的index.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>
答案 0 :(得分:0)
(基于您提供的链接中的代码。)
在mouseMovement函数中,使用mouseEvent.offsetX和mouseEvent.offsetY来获取玩家的位置,但遗憾的是Firefox不支持这些属性。不幸的是,IIRC,唯一可以跨浏览器工作的是获取画布的位置,并从事件的pageX / pageY属性中减去它。您可以使用canvas的getBoundingClientRect()方法在页面上找到它的位置。
这是一个应该在Firefox中运行的函数版本的示例:
function mouseMovement(mouseEvent) {
var canvasPosition = gameCanvas.getBoundingClientRect();
userImageX = mouseEvent.pageX - canvasPosition.left;
userImageY = mouseEvent.pageY - canvasPosition.top;
}