css - 如何将两个相同大小的 Canvas 堆叠在另一个 Canvas 旁边?

标签 css html canvas

我一直在尝试将两个相同大小的 Canvas 放在彼此的顶部并紧挨着另一个 Canvas 。让我们看看,在下图中,我希望 2 和 3 在同一个位置,在 1 旁边。 enter image description here

我尝试用下面的代码解决这个问题:

#plotCanvas {
  background-color: #fff;
  position: relative;
  top: 0px;
  left: 0px;
}

#plotCanvas_BG {
  background-color: #fff;
  position: absolute;
  top: 329px;
  left: 352px;
  background-color: transparent;
}
<div style="width: 810px; margin-left: auto; margin-right: auto;">
  <canvas width="350" height="350" id="imageCanvas" style="float: left; border: 1px solid black;"></canvas>
  <canvas width="350" height="350" id="plotCanvas" style="margin-left: 6px; border: 1px solid black;"></canvas>
  <canvas width="350" height="350" id="plotCanvas_BG" style="margin-left: 6px; border: 1px solid black;"></canvas>
</div>

如您所见,我已经手动设置了 Canvas 3(对应于“plotCanvas_BG”)的位置。然而,缺点是 Canvas 3 的位置因网络浏览器而异,如果网页大小发生变化,则位置也会发生变化。

最佳答案

使用相对定位的容器 div 将包含绝对定位的 Canvas 元素。

<div style="width: 810px; margin-left: auto; margin-right: auto;">
  <canvas width="350" height="350" id="imageCanvas" style="float: left; border: 1px solid black;"></canvas>
  <div class="container">
    <canvas width="350" height="350" id="plotCanvas" style="margin-left: 6px; border: 1px solid black;"></canvas>
    <canvas width="350" height="350" id="plotCanvas_BG" style="margin-left: 6px; border: 1px solid black;"></canvas>
  </div>
</div>

CSS

.container {
  display: inline-block;
  position: relative;
  float: left;
}

#plotCanvas,
#plotCanvas_BG {
  position: absolute;
  top: 0;
  left: 0;
  background-color: transparent;
}

#plotCanvas {
  background-color: #fff;
}

JSFiddle 演示:https://jsfiddle.net/8c8csnzk/1/

关于css - 如何将两个相同大小的 Canvas 堆叠在另一个 Canvas 旁边?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37999831/

相关文章:

html - 根据父级的高度设置宽度

css - 两个 div 用对 Angular 线分割 - CSS

html - 为什么是:first-child selector not working on div?

asp.net - 如何使我的 asp 图表在 x 方向上可滚动

html - 将图像定位在另一个图像上

c++ - 如何在MFC Dialog中添加 Canvas ?

javascript - 如何确定有效值

javascript - 添加位置: absolute div below the page bottom?后如何使div具有100%的 body 高度

Javascript选择div并更改里面的href

javascript - 如何将 Canvas 放入 Canvas 中?