0

这是我的问题:几周前我开始使用 JavaScript 和 HTML 玩游戏,上周决定继续重新格式化代码并使其更加面向对象(这实际上与我的问题没有任何关系,但值得一试将事物置于上下文中),同时使其更加面向对象,我决定将我的游戏设计分解为不同的画布,我的理解是你可以将画布层叠在一起(我已经阅读了关于使用多个画布的各种建议为了提高性能,不同的工作(包括图像缓冲),画布可以通过应用 z-index:; 在 CSS 中分层,此时我有以下 CSS 代码,我正在使用它来管理网站的设计和分层画布。

#canvas{
position: absolute;
top: 10px;
left: 100px;
z-index: 1;
background: transparent;
}
#bgCanvas{
position: absolute;
top: 10px;
left: 100px;
z-index: 0;
background: transparent;
}
#button{
position: absolute;
top: 430px;
left: 305px;
width: 116px;
border-style: solid;
border-color: red;
z-index:2;
background-color: #FFF;
}

第一个画布位于索引 1,据我所知,它位于索引 0 之上,第一个画布绘制玩家和敌人,第二个画布 bgCanvas 专用于背景,位于 z-index: 0 表示它应该位于玩家下方。然后我有第三个画布,它位于 z-index:2,它应该提供以下层次结构 2 - 游戏按钮 1 - 介绍图像、玩家和敌人图像(更新并显示在这一层上) 0 - 背景

现在回到实际问题:在之前的 JavaScript 文件中(如前所述,我正在重构该文件中的代码)我有代码可以在按钮上启用悬停效果,例如下面的代码,顺便说一下,它位于一个名为 update( ):

document.getElementById('button').style.left = canvas.width /2;
document.getElementById('button').css('z-index',1000);
document.getElementById('button').onmouseover = function(){
button.style.color = "red"; 
button.style.cursor= "pointer";
};

document.getElementById('button').onmouseout = function(){
button.style.color = "black";   
};

document.getElementById('button1').onmouseover = function(){
button1.style.color = "red";
button1.style.cursor= "pointer";    
};

document.getElementById('button1').onmouseout = function(){
button1.style.color = "black";  
};

document.getElementById('button').onclick = function(){
button.style.visibility = "hidden";
button1.style.visibility = "hidden";
gameStart = true;
};

但是,与之前的 JavaScript 文件不同,这个新文件使用不同的层来管理正在绘制的内容,因此以前可以使用的悬停和鼠标效果不会。但这是踢球者,当我将按钮的 z-index 从 2 调整为 1 时,悬停和鼠标效果会起作用。所以我的问题是,我可以在不同的 z 索引上应用悬停效果吗?或者我应该减少画布的数量等。如果您需要更多信息,我可以尝试提供并提前致谢。

4

1 回答 1

0

这个问题已经解决了哈哈。问题是这样的:函数 update() 包含 onclick、onmouseout 等。当您在 draw() 中绘制介绍屏幕并使用 if 语句 if(gameStarted===false){ 时,您需要包含 update( ) if 和 else 语句中的函数,这里是修复的代码 ^^

function draw(){
if(gameStarted === false){
startS.draw();
update();
}
else{
ctx1.drawImage(bgImage,0,0);
update();
ctx.clearRect(0,0,canvas.width, canvas.height);
p.draw();

h.draw();

requestId = window.requestAnimationFrame(draw);
}


};
于 2013-10-21T12:17:12.300 回答