简体   繁体   English

如何将两幅画布相互叠加?

[英]How do I center two canvases on top of one another?

I need to display one HTML5 canvas on top of another. 我需要在另一个上面显示一个HTML5画布。 This I have already managed in the following manner: 我已经按以下方式管理:

<canvas id="lower" width="900" height="550" style="position: absolute; left: 0; top: 0; z-index: 0;"></canvas>
<canvas id="upper" width="900" height="550" style="position: absolute; left: 0; top: 0; z-index: 1;"></canvas>

However, I can't seem to figure out how to CENTER these two canvases while keeping one on top of the other. 然而,我似乎无法弄清楚如何将这两个画布居中,同时保持一个在另一个之上。 Any ideas? 有任何想法吗?

Put them inside of a <div> with the styling: 将它们放在带有样式的<div>

div#canvasContainerId {
    position: relative;
    margin-left: auto;
    margin-right: auto;
    width: 900px;
}
  • The position: relative causes the absolute positioning of the <canvas> es to become relative to their containing <div> . position: relative导致<canvas> es的absolute定位变为相对于其包含的<div>
  • The auto margins, along with a fixed width , center the <div> . auto边距以及固定width使<div>居中。

Make an outer container with text-align:center and position:relative , make an inner container with position:relative , put the canvases inside the inner container, remove left:0;top:0; 创建一个带有text-align:center的外部容器text-align:centerposition:relative ,创建一个position:relative的内部容器,将画布放在内部容器中,删除left:0;top:0; on both canvases, and remove the position:absolute on the lower of the canvases. 在两幅画布上,并删除position:absolute在画布的下方。 And make sure in the html that the lower canvas comes before the upper canvas, like you have. 并确保在html中,较低的画布位于上部画布之前,就像你一样。

#container {
  text-align:center;
  position:relative;
}

#inner_container{
  position:relative;
}
#upper {
  z-index: 1;
}
#lower {
  position:absolute; z-index: 0;
}

http://jsfiddle.net/NW6Fx/ http://jsfiddle.net/NW6Fx/

Edit : I believe the z-index property isn't needed if you do it this way. 编辑 :我相信如果你这样做,就不需要z-index属性。 The order is just a matter of which canvas comes first in the html and which is position:relative . 顺序只是一个问题,哪个画布首先在html中,哪个是position:relative

You can put a breakline between them <br/> 你可以把它们之间的断裂线<br/>

or 要么

Might try to give each of them the following css: 可能会尝试给他们每个人以下css:

{
    margin:auto;
    clear:both;
}

With absolute positioning you should use top. 绝对定位你应该使用top。 For the first one, for example, put top: 50px . 例如,对于第一个,放top: 50px That will move the first elements 50px away from the top. 这将使第一个元素从顶部移开 50px。 For the second one, put top: 100px . 对于第二个,放top: 100px

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM