无法让画布显示在HTML后面

3

我需要帮助制作一个简单的链接网站,但我的画布无法放在文本背后。

我认为问题具体出现在我的html代码上。

我没有太多使用HTML5画布的经验,这是一个抄袭时出了差错的工作:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta content="IE=edge" http-equiv="X-UA-Compatible">
    <title>jetbrains.xyz</title>
    <link href="main.css" rel="stylesheet">
    <script src="main.js"></script>
</head>
    
<body>
    <canvas id='c'></canvas>
    <div class="mhm">
    <div class="centered">
        

                
                    <h1>⎳⎳⎳</h1>
                

        
    </div>
    
    <ul class="bmenu">
        <br />
        <li>
            <a href="http://steamcommunity.com/id/-sera/">sera</a>
        </li>
        <br />
        <li>
            <a href="">zonk</a>
        </li>
        
    </ul>
    </div>
    
   
        
</body>
        
</html>

https://jsfiddle.net/83c7npck/

1个回答

3
要更改HTML元素的层叠顺序,您需要使用z-index CSS属性。将z-index视为元素在HTML文档中与其他元素的深度或Z轴的表达式。 X和Y轴表示元素的左/右和上/下值。
Z-index允许您指定“堆叠顺序”,通过分配表示“高度”位置的数字。数字越高,该元素就会“靠近”用户进行堆叠。因此,假设一堆HTML元素每个都具有这些z-index值之一:
z-index: 1; 
z-index: 999; 
z-index: -10; 
z-index: 50; 

从最远到最近的堆叠顺序如下:

z-index: -10;
z-index: 1; 
z-index: 50; 
z-index: 999; 

警告

更改堆叠顺序意味着将元素物理放置在其他元素的上方。这意味着您会遮挡用户查看和交互的能力!在将元素放置在其他元素后面之前请仔细考虑,最好仅保留视觉效果。

为什么它不起作用

你没有对你的<canvas>元素应用任何CSS样式,因此堆叠顺序将默认为元素类型。如果没有CSS干预,HTML元素永远不会重叠。

对于canvas元素,这意味着块级元素。 您可以在Mozilla开发者网络上了解有关画布元素将如何默认行为以及如何控制它的信息。

如果您想更改元素的堆叠顺序,则需要对CSS进行一些更改:

canvas {
    position: absolute; // this removes the element from the document flow and allows other elements to float over/under it
    z-index:0; // alternately, we can simply make this '-1' to sit behind everything...
    width: 100px; // just to make it clearly visible when it's working, very handy!
    height:100px;
    background-color: red;
}

div.mhm {
    position:relative; // z-index only works if a position is set to relative or absolute
    background-color: rgba(0,0,238,0.5);
    z-index:10; // as long as this value is higher than that of the canvas' z-index, it will appear on top
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接