0

我知道有这样的问题,但我仍然找不到解决方法,我查看了控制台并看不到任何东西。有两个图像,一个应该出现在设定的坐标上,另一个是跟随鼠标的,一个不应该跟随鼠标的图像不会显示,但另一个会显示。

主.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>

提琴手

4

1 回答 1

0

(基于您提供的链接中的代码。)

在您的 mouseMovement 函数中,您使用 mouseEvent.offsetX 和 mouseEvent.offsetY 来获取玩家的位置,但不幸的是 Firefox 不支持这些属性。不幸的是,IIRC,唯一可以跨浏览器工作的是获取画布的位置,然后从事件的 pageX/pageY 属性中减去它。您可以使用画布的 getBoundingClientRect() 方法来查找它在页面上的位置。

这是也应该在 Firefox 中工作的函数版本的示例:

function mouseMovement(mouseEvent) {
    var canvasPosition = gameCanvas.getBoundingClientRect();

    userImageX = mouseEvent.pageX - canvasPosition.left;
    userImageY = mouseEvent.pageY - canvasPosition.top;
}
于 2013-09-23T03:27:04.783 回答