在Internet Explorer中,Canvas覆盖了页面

7

我正在使用以下代码将画布居中:

position:absolute;
top:50%;
left:50%;
margin-top:-200px; /* Half of canvas height */
margin-left:-275px; /* Half of canvas width */

除了IE9和10外,它在所有浏览器中都可以完美运行。在Internet Explorer中,它覆盖整个页面。是否可能支持在IE中居中canvas?


你在 CSS 中指定了宽度吗? - Bram Vanroy
@Pete http://pastebin.com/wMz33J5Q - user1431627
@user1431627 你需要绝对定位吗? - sylwia
@sylwia 我需要它,因为如果它不在那里,它就会上移到左上角。 - user1431627
1个回答

7
使用margin: 0 auto;display: block;进行居中在几乎所有浏览器中都可以运行,对于支持<canvas>的浏览器肯定可以运行。
实时示例:http://jsbin.com/ovoziv/2 HTML
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Centring Canvas</title>
</head>
<body>

  <canvas></canvas>

</body>
</html>

CSS

canvas {
  display: block;
  background: #FFFFB7;
  width: 550px;
  height: 400px;
  margin: 0 auto;
}

编辑:更新答案以垂直居中。这段CSS代码可以解决问题:

canvas {
    background-color: #FFFFB7;
    width: 550px;
    height: 400px;
    position: absolute;
    top: 50%;
    left: 50%;
    margin-left: -275px;
    margin-top: -200px;
}

现在来解释一下。我们首先使用position: absolute将画布与顶部和左侧的偏移量都设置为50%,通过设置topleft50%。然后,因为您的画布具有静态大小,我们为宽度和大小的一半(550x400/2 = 275x200)添加了负边距(当元素没有绝对定位时,永远不要这样做):margin-left: -275px; margin-top: -200px;
现在画布将显示在屏幕中心。如果您在另一个元素内执行此操作并希望将其居中对齐,则可以尝试将position: relative;添加到该元素中,以便它使用其边界而不是body的边界。
示例请参见:http://jsbin.com/ovoziv/6

但它并没有垂直居中,只有水平居中。 - user1431627
@user1431627 我更新了我的答案。基本上是你的代码,但似乎仍然可以工作。 - Broxzier
1
我找出了问题所在,IE的设置被设置为整页缩放。有些尴尬 :P - user1431627

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