Html 在 html5 中的画布上放置一个 div

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15861485/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 07:18:33  来源:igfitidea点击:

placing a div over a canvas in html5

csshtmlcanvascenter

提问by André Hincu

I am trying to place a div element over a canvas (it is for a game) on the center of my page. It is about a startscreen that I want to show over the canvas, before starting the game(this startscreen has options like "Play game", "Settings" etc). The problem is that I cannnot get this done, I have searched a lot on Google, I have seen a lot of examples, but none of them seems to be working for me. Here is my code:

我正在尝试将一个 div 元素放置在我页面中心的画布上(它用于游戏)。这是关于我想在开始游戏之前在画布上显示的开始屏幕(此开始屏幕具有“玩游戏”、“设置”等选项)。问题是我无法完成这项工作,我在谷歌上搜索了很多,我看过很多例子,但似乎没有一个对我有用。这是我的代码:

<div id="gamecontainer">
            <canvas id="myCanvas" width="800" height="600">
                Sorry, <strong>CANVAS</strong> is not supported by your browser. Get a more recent one to play my game!
            </canvas>

            <div id="gamestartscreen" class="gamelayer">
                <img src="images/icons/play.png" alt="Play Game" onclick="alert('ceve');"><br>
                <img src="images/icons/settings.png" alt="Settings">
            </div>
</div>

here is the css:

这是CSS:

#gamecontainer {
    width: 800px;
    height: 600px;
    background-color: beige;
    border: 1px solid black;
    position: relative;
    margin: 0 auto;
}

.gamelayer {
    width: 800px;
    height: 600px;
    position: absolute;
    display: none;
    z-index: 0;
}


/* Screen for the main menu (Like Play, Settings, etc.) */
#gamestartscreen {
    position: relative;
    margin: 0 auto;
}

#gamestartscreen img {
    margin: 10px;
    cursor: pointer;
}

Could someone please tell me where I am doing it wrong?

有人可以告诉我我哪里做错了吗?

回答by Radu Chelariu

The problem was that the canvas layer was in its native static positioning, while the gamestart div was in relative positioning with no positive z-index value. Essentially, you jut have to set the canvas element to position: absoluteor even position: relative, while having a >1 z-index for the startstreen div. This JSFiddleshould make it all clear. Cheers!

问题是画布层处于其原生静态定位,而游戏开始 div 处于相对定位,没有正 z-index 值。本质上,您只需将 canvas 元素设置为position: absolute或 even position: relative,同时为开始树 div 设置 >1 z-index。这个JSFiddle应该说明一切。干杯!