我正试图在我的游戏中输入鼠标;任何帮助将不胜感激。
我在init()函数中调用事件监听器,并且我有mouseMoved()和mouseClicked()函数。但我一直没有得到任何回应。
(我被要求为这个项目制作一个jsFiddle,所以here就是这样。由于某些原因,它不会渲染图像。但是一旦有输入,左上角应该有文字显示鼠标坐标。此外,当您单击画布时,您应该收到警报。)
var canvasBg = document.getElementById('canvasBg');
var ctxBg = canvasBg.getContext('2d');
var canvasEntities = document.getElementById('entities');
var entitiesCtx = canvasEntities.getContext('2d');
var isPlaying = false;
var player;
var enemy;
var mouseX, mouseY;
var playerImg = new Image();
playerImg.src = 'http://placekitten.com/g/50/50';
var enemyImg = new Image();
enemyImg.src = 'http://placehold.it/50x50';
window.onload = init;
var requestAnimFrame = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 60);
};
// main functions
function init() {
console.debug('init()');
player = new Entity(250, // xpos
225, // ypos
0, // xd
0, // yd
3, // speed
50, // width
50, // height
playerImg, // imgSrc
true); // player?
enemy = new Entity(500,225,0,0,1,25,25,enemyImg,false);
canvasBg.addEventListener('mousemove', mouseMoved, false);
canvasBg.addEventListener('click', mouseClicked, false);
startLoop();
}
function loop() {
// console.debug('game loop');
if(isPlaying){
update();
draw();
requestAnimFrame(loop);
}
}
function startLoop() {
isPlaying = true;
loop();
}
function stopLoop() {
isPlaying = false;
}
function clearAllCtx() {
ctxBg.clearRect(0, 0, canvasBg.width, canvasBg.height);
Entity.clearCtx();
}
function draw(){
clearAllCtx();
player.draw();
enemy.draw();
}
function update(){
player.update();
}
// end of main functions
// input handling
function mouseMoved(e) {
mouseX = e.layerX - canvasBg.offsetLeft;
mouseY = e.layerY - canvasBg.offsetTop;
document.getElementById('mouseCoors').innerHTML = 'X: ' + mouseX + ' Y: ' + mouseY;
}
function mouseClicked(e) {
alert('You clicked the mouse!');
}
// end of input handling
// Entity functions
function Entity(xpos, ypos, xd, yd, speed, width, height, imagesrc, player) {
this.xpos = xpos;
this.ypos = ypos;
this.xd = xd;
this.yd = yd;
this.speed = speed;
this.width = width;
this.height = height;
this.imagesrc = imagesrc;
this.player = player;
}
Entity.clearCtx = function(){
entitiesCtx.clearRect(0,0,canvasBg.width,canvasBg.height);
};
Entity.prototype.draw = function () {
entitiesCtx.drawImage(this.imagesrc, this.xpos, this.ypos);
};
Entity.prototype.update = function () {
this.xpos += this.xd;
this.ypos -= this.yd;
};
// end of Entity functions
答案 0 :(得分:0)
所以有一些事情正在发生,首先是小提琴加载设置不正确,一旦我改变它没有包裹在身体一切正常。
你遇到的实际问题是由于背景画布在实体画布下,所以它无法获得任何鼠标事件。
一种解决方案是使用pointer-events并在实体画布上将其设置为无pointer-events: none
。
<强> Live Demo 强>
#entities {
margin: -500px auto;
pointer-events: none;
}
如果您需要更广泛的浏览器支持,另一个选择是让entities
画布代替捕获鼠标事件。
<强> Live Demo of Option 2 强>