定位重叠画布

时间:2014-03-14 19:39:20

标签: javascript html css canvas

我有一个应该显示折线图的页面。顶部有一个标题,中间是图形,然后是下面的表格。它的布局大致如下:

<div>
    <h1>Title</h1>
</div>
<div>
    <canvas1></canvas>
    <canvas2></canvas>
</div>
<div>
    <table></table>
</div>

现在每个'div'区块彼此分开,这很好。然而,尽管具有不同的z-index值,但两个画布彼此相邻而不是堆叠在顶部。我已经读过它们的位置值都应该设置为绝对值,但每当我这样做时,表格会立即移动到画布顶部。

我需要将div和它们内部的元素设置为div和它们之间的元素(两个都是相同的尺寸),而不需要在div的顶部堆叠任何其他位置和显示值?

编辑:这是fiddle

2 个答案:

答案 0 :(得分:1)

<强> HTML:

将2幅画布包裹在包装div中。

<div id="wrapper">
    <canvas id="canvasBottom" width=300 height=200></canvas>
    <canvas id="canvasTop" width=300 height=200></canvas>
</div>

<强> CSS:

将2幅画布放置在同一顶部和底部。相对于包装div而言。

#wrapper{
    position:relative;
    width:300px;
    height:200px;
}
#canvasTop,#canvasBottom{
    position:absolute; top:0px; left:0px;
    width:300px;
    height:200px;
}

答案 1 :(得分:0)

如果将两个画布的“ position”属性设置为“ absolute”,则两个画布将粘贴到父元素,例如div。   桌子在画布上移动的原因是,从某种意义上说,桌子“忽略了”您的画布,并且其位置就好像没有画布一样。   您应该做的是保留画布的绝对位置值,并将表格的“顶部”值设置为画布的高度,然后表格就在画布的下方。   让我举一个例子:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Animal World</title>
    <style>
        canvas {
            width: 50%;
            height: 100px;
            position: absolute;
        }
        #dog {
            z-index: 1;

        }
        #cat {
            z-index: 0;
            background-color: blue;
        }
        table{
            background-color: rgb(196, 255, 216);
            position: relative;
            top: 100px;
            border-collapse: collapse;
        }
        caption{
            font-weight: bolder;
            font-size: 2em;
            background-color:  rgb(196, 255, 216);
            border: 1px groove lightblue;
        }
        td,th{
            border: 1px groove lightblue;
           
        }
        
    </style>
</head>
<body>
    <div>
        <h1>Animal</h1>
    </div>
    <div id = "canvas">
        <canvas id = "dog"></canvas>
        <canvas id = "cat"></canvas>
    </div>
    <script>
        var dog = document.getElementById('dog');
        var cat = document.getElementById('cat');
        var dog_ctx = dog.getContext('2d');
        var cat_ctx = dog.getContext('2d');
        dog_ctx.fillStyle = "red";
        dog_ctx.fillRect(20, 20, 20, 20);
    </script>
    
    <div class = "table">
            <table>
                <caption>Animal</caption>
                <tr>
                    <th>Dog</th>
                    <th>Panda</th>
                    <th>Cat</th>
                </tr>
                <tr>
                    <td>middle</td>
                    <td>large</td>
                    <td>small</td>
                </tr>
            </table>
    </div>
</body>
</html>

相关问题