如何在html5中心画布 [英] How to center canvas in html5

查看:160
本文介绍了如何在html5中心画布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找一个解决方案,现在,但没有找到任何东西。也许这只是我的搜索字词。
好​​吧,我想根据浏览器窗口的大小来制作画布中心。画布为800x600。
如果窗口低于800x600,它应该调整大小(但这不是很重要的)

I've been searching for a solution for a while now, but haven't found anything. Maybe it's just my search terms. Well, I'm trying to make the canvas center according to the size of the browser window. The canvas is 800x600. And if the window gets below 800x600, it should resize as well(but that's not very important at the moment)

推荐答案

给画布以下css样式属性:

Give the canvas the following css style properties:

canvas {
    padding-left: 0;
    padding-right: 0;
    margin-left: auto;
    margin-right: auto;
    display: block;
    width: 800px;
}






/ strong>


Edit

由于这个答案很受欢迎,我想补充一点细节。

Since this answer is quite popular, let me add a little bit more details.

上面的属性会水平将画布,div或任何其他节点与其父节点相关联。无需更改顶部或底部边距和padding。你指定一个宽度,并让浏览器用剩余的空间填充自动边距。

The above properties will horizontally center the canvas, div or whatever other node you have relative to it's parent. There is no need to change the top or bottom margins and paddings. You specify a width and let the browser fill the remaining space with the auto margins.

但是,如果你想输入less,你可以使用任何css的速记属性,例如

However, if you want to type less, you could use whatever css shorthand properties you wish, such as

canvas {
    padding: 0;
    margin: auto;
    display: block;
    width: 800px;
}

以画布垂直 。您需要使用绝对定位,并指定宽度和高度。然后将左,右,顶部和底部属性设置为0,并让浏览器使用自动边距填充剩余空间。

Centering the canvas vertically requires a different approach however. You need to use absolute positioning, and specify both the width and the height. Then set the left, right, top and bottom properties to 0 and let the browser fill the remaining space with the auto margins.

canvas {
    padding: 0;
    margin: auto;
    display: block;
    width: 800px;
    height: 600px;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
}

画布将基于第一个父元素 position 设置为相对 absolute

The canvas will center itself based on the first parent element that has position set to relative or absolute, or the body if none is found.

另一种方法是使用 display:flex ,可在IE11中使用

Another approach would be to use display: flex, that is available in IE11

此外,请确保使用最近的doctype(例如xhtml或html 5)。

Also, make sure you use a recent doctype such as xhtml or html 5.

这篇关于如何在html5中心画布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆